Zebra0.com

csharp listbox

Open and Read a File

Write the code for readfile as shown below. For now, you can call this from mnuOpen..

private void readfile()
{
   // Set the filter to show text files or all files.
   openFileDialog1.Filter = "Text Files|*.txt|All Files|*.*";
   openFileDialog1.ShowDialog();
   if (openFileDialog1.FileName != "")
   {
       currentFileName = openFileDialog1.FileName;
       this.Text = currentFileName;
       // Read the entire file into an array.
       string[] lines = System.IO.File.ReadAllLines(openFileDialog1.FileName);
       // Add each line to the list box.
       foreach (string line in lines)
       {
           lstData.Items.Add(line);
        }
        // The file has just been read, so there are no changes yet.
        changed = false;
    }
}

To Do: Call readfile from mnuOpen. Make sure this works before proceeding.

End of lesson, Next lesson: ListBox Manager Part 2: Printing in C#