ListBox Manager in C#
Write to File from ListBox
Write the code for writefile as shown below. For now, you can call this from mnuSave.
private void writefile()
{
// Filename is "Untitled" initially, on mnuNew and mnuSaveAs.
if (currentFileName == "Untitled")
{
saveFileDialog1.Filter = "Text Files|*.txt|All Files|*.*";
saveFileDialog1.ShowDialog();
// Filename is "" if cancel selected.
if (saveFileDialog1.FileName != "")
{
currentFileName = saveFileDialog1.FileName;
Text = currentFileName;
}
}
if (currentFileName!="Untitled")
{
using (System.IO.StreamWriter file =
new System.IO.StreamWriter(currentFileName))
{
// Write each item in list box to file.
foreach (string item in lstData.Items)
{
file.WriteLine(item);
}
file.Close();
// We just saved, so no changes since last save.
changed = false;
}
}
}
To Do: Call writefile from mnuSave. Make sure this works before proceeding.
That's all! Congratulations on completing all of the lessons in csharp!