【问题标题】:Saving windows form listbox to a text file C#将 Windows 窗体列表框保存到文本文件 C#
【发布时间】:2013-04-27 22:12:34
【问题描述】:

我正在尝试将列表框的内容保存到文本文件中。它可以工作,但是我得到的不是输入到列表框中的文本,而是:

System.Windows.Forms.ListBox+ObjectCollection

这是我用于表单本身的相关代码。

listString noted = new listString();
        noted.newItem = textBox2.Text;
        listBox1.Items.Add(textBox2.Text);

        var radioOne = radioButton1.Checked;

        var radioTwo = radioButton2.Checked;

        var radioThree = radioButton3.Checked;

        if (radioButton1.Checked == true)
        {
            using (StreamWriter sw = new StreamWriter("C:\\windowsNotes.txt"))
            {
                sw.Write(listBox1.Items);
            }
        }
        else if (radioButton2.Checked == true)
        {
            using (StreamWriter sw = new StreamWriter("C:\\Users\\windowsNotes.txt"))
            {
                sw.Write(listBox1.Items);
            }
        }
        else if (radioButton3.Checked == true)
        {
            using (StreamWriter sw = new StreamWriter("../../../../windowsNotes.txt"))
            {
                sw.Write(listBox1.Items);
            }
        }
        else
        {
            MessageBox.Show("Please select a file path.");
        }
    }

这个类只是一个简单的类:

 namespace Decisions
 {
     public class listString
     {
         public string newItem {get; set;}

         public override string ToString()
         {
             return string.Format("{0}", this.newItem);
         }
     }
 }

【问题讨论】:

  • 循环 listBox1.Items 并写入它们

标签: c# text listbox save


【解决方案1】:

你不能只做

   sw.Write(listBox1.Items);

因为它在集合对象本身上调用 .ToString()。

尝试类似:

   sw.Write(String.Join(Environment.NewLine, listBox1.Items));

或者循环遍历每个项目并 ToString 单个项目。

【讨论】:

  • Opps...谢谢。我忘了添加 - 这是未经测试的代码,但原理应该有效
【解决方案2】:

你将不得不一一写下这些项目:

using (StreamWriter sw = new StreamWriter("C:\\windowsNotes.txt") {
    foreach (var item in listBox1.Items) {
        sw.WriteLine(item.ToString());
    }
}

【讨论】:

    【解决方案3】:

    您正在将集合的 ToString 写入输出流,而不是集合的元素。对集合进行迭代并单独输出每个都可以,我确信有一种简洁的 Linq(或更明显)的方式来做到这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-04
      • 1970-01-01
      • 2012-01-23
      • 2018-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多