简体   繁体   中英

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

使用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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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