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

时间:2011-05-10 04:48:05

标签: c# listbox

我正在使用.Net 3.5 - 我在将列表框项目尝试到文本文件时遇到问题。我正在使用此代码:

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

此行发生错误:

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

错误是:

  

无法将“SampleData”类型的对象强制转换为“System.String”类型   请帮帮我

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

您应该在类中重写ToString方法,您要将哪些实例写入文件。在ToString方法中,您应格式化正确的输出字符串:

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

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

然后使用

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

答案 2 :(得分:0)

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"