How to save text from the list?

Can I use StreamWriter function to save text to 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(); 
                }

      

+3


source to share


3 answers


The ListBox.Text property only works on the selected item. You, I suspect, need all the elements. If the ListBox strings are stored, this can be done:



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

      

+2


source


You have to use string in ListBox SelectedItem



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

      

+1


source


If you want to store all items in your Listbox using StreamWriter, loop through all items and pass them by string or string builder, then write in 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 to select the selected text, you can simply use SelectedItem:

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

      

0


source







All Articles