[英]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. 我有2个表单,在
Form1
有一个按钮,在Form2
有带数据的ListBox
。 What I want is to click the button on Form1
and save the data from the Form2
ListBox
in a text file. 我想要的是单击
Form1
上的按钮,然后将Form2
ListBox
中的数据保存到文本文件中。
What I have tried: 我尝试过的
This is button on Form1 这是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. 但这不起作用,请始终将文件保存为空白。
myForm.listBox.Items.OfType<string>()
is going to return an empty enumerable since Items
contains ListBoxItem instances 因为
Items
包含ListBoxItem实例,所以将返回一个空的可枚举
The following should work: 以下应该工作:
ListBox listBox = myForm.listBox;
IEnumerable<string> lines = listBox.Items.Select(item => listBox.GetItemText(item));
File.WriteAllLines(sfd.FileName, lines);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.