Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Good morning!
I have a doubt, I searched a lot but found nothing, I hope someone can help me.
Very well.

I have 2 Forms, on Form1 I have a button and in the Form2 I have a ListBox with data.
What I want is to click the button on Form1 and save the data from the Form2 ListBox in a text file.

The data types that are in the listbox are fairly straightforward, the listbox has at most 12 line, and each row has only one word.

What I have tried:

This is button on Form1

private void toolStripButtonGuardar_Click(object sender, EventArgs e)
        {
            var myForm = new FormVer();

            //Escolher onde salvar o arquivo
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            sfd.Title = "Guardar";
            sfd.Filter = "Arquivos TXT (*.txt)|*.txt";

            if (sfd.ShowDialog() == DialogResult.OK)
            {
                try
                {

                    File.WriteAllLines(sfd.FileName, myForm.listBox.Items.OfType<string>());

                    //Mensagem de confirmação
                    MessageBox.Show("Guardado com sucesso", "Notificação", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }


But it doesn't work, always save the file blank.
Posted
Updated 11-Aug-17 2:36am
v2
Comments
Alan N 11-Aug-17 8:46am    
Why are you creating a new form? You need a reference to the existing FormVer.

1 solution

C#
File.WriteAllText(sfd.FileName, string.Join("|", myForm.listBox.Items.OfType<string>()));

Update: The above solution is based on the information provided. You imply that the data in the list are simple strings, So the above code joins strings and writes them to disk as a continuous string.

If you are using complex objects like classes, then you need to do more work to serialize the object before you can write it to disk.

Here is a [Newtonsoft] JSON helper for serializing and deserializing:
C#
using Newtonsoft.Json;
using System.Collections.Generic;

namespace DotNet.Shared.Helpers
{
    public static class JsonConverter
    {
        public static string FromClass<T>(T data, bool isEmptyToNull = false, JsonSerializerSettings jsonSettings = null)
        {
            string response = string.Empty;

            if (!EqualityComparer<T>.Default.Equals(data, default(T)))
                response = JsonConvert.SerializeObject(data, jsonSettings);

            return isEmptyToNull ? (response == "{}" ? "null" : response) : response;
        }

        public static T ToClass<T>(string data, JsonSerializerSettings jsonSettings = null)
        {
            var response = default(T);

            if (!string.IsNullOrEmpty(data))
                response = jsonSettings == null
                    ? JsonConvert.DeserializeObject<T>(data)
                    : JsonConvert.DeserializeObject<T>(data, jsonSettings);

            return response;
        }
    }
}

And to use:
C#
File.WriteAllText(sfd.FileName, JsonConverter.FromClass(listBox1.Items.OfType<Person>()));


UPDATE #2: You will always have blank files because of this line:
C#
var myForm = new FormVer();

Instead of creating a new form with empty data, you need to point to the active form with the data. Something like:
C#
var myForm = Application.OpenForms[nameof(FormVer)];
 
Share this answer
 
v3
Comments
Member 13347457 5-Aug-17 10:19am    
I tried this but it gives error, says "" Cannot convert from ´ string ´ to ´ string [] ´
I think the problem is the "MyForm"
Because I did a test, but only I did everything on the same form, ie in the Form2, as the button and the ListBox were on the same form, it went all right and saved it all right.
But only that I need to do even with the button on Form1 and the listbox Form2, ie I need to call the ListBox.
I believe the problem is when calling the ListBox
But I don't know how to resolve
Graeme_Grant 5-Aug-17 17:55pm    
I've updated the solution.
Member 13347457 11-Aug-17 8:48am    
Please I have updated my question, please take a look.
My strings are simple.

Okay, I'm very bad, but I'm going to try to explain.
I did a test on the same form of the ListBox and my code worked perfectly, it worked because I wouldn't need to call the ListBox from another form, just while I was trying to save the information that was on Form1 through the Form2 I used this code "File. WriteAllLines (SFD. FileName, MyForm. ListBox. Items. OfType <string> ()); ", I now as I was in the same form I used this" File. WriteAllLines (SFD. FileName, ListBox. Items. OfType <string> ()); "

So I know the error is when calling the ListBox, does not work that way.
Please if not do I know ask me again, I need help but I am not able to explain I am terribly sorry.
Graeme_Grant 11-Aug-17 8:50am    
Have a read of UPDATE #2... I think that I found your problem...
Member 13347457 15-Aug-17 7:26am    
Just keep giving me a mistake I've tried to resolve and I haven't figured it out.
If I put this line of code like you said, "var MyForm = Application. OpenForms [Nameof (FormVer)];", it will give error in the line of code where I call the ListBox, "File. WriteAllLines (SFD." FileName, MyForm. ListBox. Items. OfType <string> ());, gives an exact error in the word ListBox.
says that ' form ' does not contain a definition for ' listbox ' and in the extension method ' ListBox ' accepting a first argument of type ' form ' could be found.
What does this mean?
Thank you for trying to help me.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900