Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving the items of a listbox to a text file

How can I save the contents of my listbox items to a text file using a SaveFileDialog?

I also want to add additional information to the text file and also add a MessageBox saying saved when it's been successful.

like image 318
roller Avatar asked Feb 19 '10 00:02

roller


People also ask

How do I display items in ListBox?

Step 1: Create a list box using the ListBox() constructor is provided by the ListBox class. // Creating ListBox using ListBox class constructor ListBox mylist = new ListBox(); Step 2: After creating ListBox, set the Items property of the ListBox provided by the ListBox class.

How do I move an item from one ListBox to another?

In the Toolbox, click the Command Button control. On the UserForm, drag to draw an outline for the first command button, between the two listboxes. Use the command button control to draw 3 more buttons, or copy and paste the first button. Below the listboxes, add one more button, that will be used to close the form.

How does ListBox work in C#?

In Windows Forms, ListBox control is used to show multiple elements in a list, from which a user can select one or more elements and the elements are generally displayed in multiple columns. The ListBox class is used to represent the windows list box and also provide different types of properties, methods, and events.


2 Answers

        var saveFile = new SaveFileDialog();
        saveFile.Filter = "Text (*.txt)|*.txt";
        if (saveFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            using (var sw = new StreamWriter(saveFile.FileName, false))
                foreach (var item in listBox1.Items)
                    sw.Write(item.ToString() + Environment.NewLine);
            MessageBox.Show("Success");
        }

Also take note the StreamWriter has a Type of Encoding.

like image 51
spajce Avatar answered Sep 30 '22 05:09

spajce


this should do it.

private void button1_Click(object sender, EventArgs e)
{
    OpenFileDialog f = new OpenFileDialog();

    f.ShowDialog();                 

    ListBox l = new ListBox();
    l.Items.Add("one");
    l.Items.Add("two");
    l.Items.Add("three");
    l.Items.Add("four");

    string textout = "";

    // assume the li is a string - will fail if not
    foreach (string li in l.Items)
    {
        textout = textout + li + Environment.NewLine;
    }

    textout = "extra stuff at the top" + Environment.NewLine + textout + "extra stuff at the bottom";
    File.WriteAllText(f.FileName, textout);

    MessageBox.Show("all saved!");
}
like image 29
nbushnell Avatar answered Sep 30 '22 05:09

nbushnell