Amauri
Amauri

Reputation: 1

How can I save a listbox in a text file

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.

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.

Upvotes: 0

Views: 96

Answers (1)

vc 74
vc 74

Reputation: 38179

myForm.listBox.Items.OfType<string>()

is going to return an empty enumerable since Items contains ListBoxItem instances

The following should work:

ListBox listBox = myForm.listBox;
IEnumerable<string> lines = listBox.Items.Select(item => listBox.GetItemText(item));

File.WriteAllLines(sfd.FileName, lines);

Upvotes: 1

Related Questions