开发者

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. 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 selectedDC开发者_如何转开发XText = (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


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


You should override ToString method in class, which instances you want to write into file. Inside ToString method you should format correct output string:

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"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜