C# 如何在文本文件中保存列表框项目
我使用的是.NET3.5-我在尝试将列表框项目添加到文本文件时遇到问题。我正在使用以下代码:C# 如何在文本文件中保存列表框项目,c#,listbox,C#,Listbox,我使用的是.NET3.5-我在尝试将列表框项目添加到文本文件时遇到问题。我正在使用以下代码: if (lbselected.Items.Count != 0) { string Path = Application.StartupPath + "\\ClientSelected_DCX.txt"; StreamWriter writer = new StreamWriter(Path); int selectedDCXCount = System.Convert.ToInt32(lb
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”类型
请帮帮我
使用
string selectedDCXText=lbselected.Items[i].ToString()代码>您应该重写类中的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());
确保已在SampleData类中重写ToString方法,如下所示:
公共类抽样数据
{
//这只是一个示例属性。您应该用自己的属性替换它。
公共字符串名称{get;set;}
公共重写字符串ToString()
{
//指定要作为此对象的字符串表示形式返回的所有属性。
返回名称;
}
}
现在不是下面这行,
string selectedDCXText=(string)(lbselected.Items[i]);
你应使用:
字符串selectedDCXText=lbselected.Items[i].ToString();
除非在类中重写了ToString方法,否则ToString方法将只输出类限定名,例如“Sample.SampleData”
虽然他可能想要整个对象。谢谢,它正在保存,但它正在将列表项写入文本文件,它没有保存项名称,而是将这一行保存在文本文件Realtime\u ALL.Form1+SampleData Realtime\u ALL.Form1+SampleData感谢它的工作,但除此之外,像这样的每个项都会添加一个1-1个月1,铝制-2个月1,铝制-3个月1,ATF-1个月1,ATF-2个月1,BRCRUDEOIL-1个月1,如何卸下此1。
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"