【发布时间】:2017-08-15 11:31:55
【问题描述】:
我有 2 个表单,在 Form1 我有一个按钮,在 Form2 我有一个带有数据的 ListBox。
我想要的是单击Form1 上的按钮并将Form2 ListBox 中的数据保存在文本文件中。
我尝试过的:
这是 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);
}
}
}
但它不起作用,总是将文件保存为空白。
【问题讨论】:
-
好吧,
myForm.listBox.Items.OfType<string>()会返回任何东西吗?如果myForm是Form,则不清楚您对它的期望是什么,因为您实际上从未向用户显示该表单。因此,它的控件从未进行过任何交互。您实际上想从该表单中得到什么? -
var myForm = new FormVer();-- 是你的问题(嗯,其中之一)。您创建了一个全新的、完全独立的FormVer实例(假设)它的列表框中没有 有任何数据。您需要使FormVer的实例具有 以某种方式在此处可用的数据。 -
如何创建实例?我必须创建一个类吗?抱歉,我是新手,我不知道从哪里开始。