简体   繁体   English

如何在文本文件中保存列表框项目

[英]how to save listbox items in a text file

I am using .Net 3.5 - I have a problem trying list box items to a text file. 我正在使用.Net 3.5 - 我在将列表框项目尝试到文本文件时遇到问题。 I am using this code: 我正在使用此代码:

if (lbselected.Items.Count != 0) {
  string Path = Application.StartupPath + "\\ClientSelected_DCX.txt";
  StreamWriter writer = new StreamWriter(Path);
  int selectedDCXCount = System.Convert.ToInt32(lbselected.Items.Count);
  int i = 0;

  while (i != selectedDCXCount) {
    string selectedDCXText = (string)(lbselected.Items[i]);
    writer.WriteLine(selectedDCXText);
    i++;
  }

  writer.Close();
  writer.Dispose();
}

MessageBox.Show("Selected list has been saved", "Success", MessageBoxButtons.OK);

An error occurs for this line: 此行发生错误:

string selectedDCXText = (string)(lbselected.Items[i]);

The error is: 错误是:

Unable to cast object of type 'SampleData' to type 'System.String' please help me 无法将'SampleData'类型的对象强制转换为'System.String',请帮帮我

使用string selectedDCXText = lbselected.Items[i].ToString();

You should override ToString method in class, which instances you want to write into file. 您应该在类中重写ToString方法,您要将哪些实例写入文件。 Inside ToString method you should format correct output string: 在ToString方法内部,您应格式化正确的输出字符串:

class SampleData
{
   public string Name
   {
       get;set;
   }
   public int Id
   {
       get;set;
   }

   public override string ToString()
   {
       return this.Name + this.Id;
   }
}

And then use 然后使用

string selectedDCXText = (string)(lbselected.Items[i].ToString());
Make sure that you have overridden the ToString method in your SampleData class like below:

                public class SampleData
{

                                // This is just a sample property. you should replace it with your own properties.
                                public string Name { get; set; }

                                public override string ToString()
                                {
                                    // concat all the properties you wish to return as the string representation of this object.
                                    return Name;
                                }

}

Now instead of the following line,
    string selectedDCXText = (string)(lbselected.Items[i]); 
you should use:
    string selectedDCXText = lbselected.Items[i].ToString();

Unless you have ToString method overridden in your class, the ToString method will only output class qualified name E.G. "Sample.SampleData"

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

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