Reputation: 1
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
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