【问题标题】:How can I save a listbox in a text file如何将列表框保存在文本文件中
【发布时间】: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&lt;string&gt;() 会返回任何东西吗?如果myFormForm,则不清楚您对它的期望是什么,因为您实际上从未向用户显示该表单。因此,它的控件从未进行过任何交互。您实际上想从该表单中得到什么?
  • var myForm = new FormVer(); -- 是你的问题(嗯,其中之一)。您创建了一个全新的、完全独立的FormVer 实例(假设)它的列表框中没有 有任何数据。您需要使FormVer 的实例具有 以某种方式在此处可用的数据。
  • 如何创建实例?我必须创建一个类吗?抱歉,我是新手,我不知道从哪里开始。

标签: c# winforms listbox


【解决方案1】:
myForm.listBox.Items.OfType<string>()

将返回一个空的可枚举,因为 Items 包含 ListBoxItem 实例

以下应该有效:

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

File.WriteAllLines(sfd.FileName, lines);

【讨论】:

  • 我尝试了您的示例并在“选择”中给出错误,说它不包含定义。
  • @Amauri 确保您的使用中有System.Linq
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-02-11
  • 2018-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多