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.
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.
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.
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.
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.
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!");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With