6.7. Exploring the File Dialog

Nobody really wants to type in a file name, let alone a file name and path. What users want is a directory tree dialog window to pop up that they can navigate and select from. The first step, as always, is to drag the control onto the form. Unlike the other controls so far, OpenFileDialog is not a visible control. It does not display in the form. Rather we need to associate it with a visible control. The usual suspect is an Open menu item.

When the user clicks the menu item, we need to respond by invoking the openFileDialog1 object's ShowDialog() member function. The menu item event handler looks like this:

private void menuItem2_Click(object sender, System.EventArgs e)
{
      Text = "Open Menu Item Clicked";
      openFileDialog1.ShowDialog();
}

The ShowDialog() method launches the file dialog window and handles everything until the user clicks Open. At that point, a FileOk event is raised associated with openFileDialog1. (If Cancel is clicked, no event is raised.) Our event handler retrieves the selected file from the openFileDialog1 object. It then reads the file and places the text in a list box. It also writes the path and file names into an adjacent text box. It looks like this:

protected void openFileDialog1_FileOk( object sender,
                     ComponentModel.CancelEventArgs e)
{
      // get file name selected by user ...
      textBox.Text =  openFileDialog1.FileName;

      // open the file ...
      StreamReader strmInput =
               new StreamReader(openFileDialog1.FileName );

      // read through and add each line to the list box
      string item;
      while (( item = strmInput.ReadLine() ) != null )
               listBox1.Items.Add( item );

      // close the StreamReader
      strmInput.Close();

      // repaint the list box and
      // have no item be treated as selected ...
      listBox1.Invalidate();
      listBox1.SelectedIndex = -1;
}

There is also a SaveFileDialog control.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.45.5