A.Ran
A.Ran

Reputation: 49

How to save text from the ListBox?

Can I use the "StreamWriter" function to save the text in the ListBox?

private void button3_Click(object sender, EventArgs e)
        {

            SaveFileDialog saveFile1 = new SaveFileDialog();
            saveFile1.DefaultExt = "*.txt";
            saveFile1.Filter = "Text files|*.txt";
            if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
            saveFile1.FileName.Length > 0)
            {
                using (StreamWriter sw = new StreamWriter(saveFile1.FileName, true))

                {
                    sw.WriteLine(listBox1.Text);
                    sw.Close(); 
                }

Upvotes: 3

Views: 331

Answers (3)

Liliana96
Liliana96

Reputation: 85

Property ListBox.Text only works with the selected item. You, I suspect, need all the elements. If the ListBox rows are stored, it is possible to do so:

File.WriteAllLines(saveFile1.FileName, listBox1.Items.OfType<string>());

Upvotes: 2

Willy David Jr
Willy David Jr

Reputation: 9171

If you want to save all items on your Listbox using StreamWriter, loop through all items and pass it on a string, or stringbuilder then write it on your file:

using (StreamWriter sw = new StreamWriter(saveFile1.FileName, true))
   {
      string text = "";
      foreach (var item in listBox1.Items)
       {
         text += item.ToString() + Environment.NewLine; //I added new line per list.
       }
    sw.WriteLine(text);
    sw.Close();
   }

If you want the selected text instead, you can just use the SelectedItem:

using (StreamWriter sw = new StreamWriter(saveFile1.FileName, true))
      {
         sw.WriteLine(listBox1.SelectedItem);
         sw.Close();
      }

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222720

You should use string SelectedItem of the ListBox

  using (StreamWriter sw = new StreamWriter(saveFile1.FileName, true))
    {
        sw.WriteLine(listBox1.GetItemText(listBox1.SelectedItem));
        sw.Close(); 
    }

Upvotes: 1

Related Questions