繁体   English   中英

将窗体列表框保存到文本文件C#

[英]Saving windows form listbox to a text file C#

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

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);
         }
     }
 }

您必须逐个编写项目:

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

你不能这样做

   sw.Write(listBox1.Items);

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

尝试类似的东西:

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

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

您正在将集合的ToString写入输出流而不是集合的元素。 对集合进行迭代并逐个输出每个集合都可以正常工作,我确信有一种简单的Linq(甚至更明显)的方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM