Exception Handling

  • Thread starter Thread starter AMP
  • Start date Start date
A

AMP

Hello,
I have the following code in a menu function.
If no fileis clicked (Cancel) it throws an exception.I try to write a
catch try catch statement but opnFile is not visable in the catch
statement I just want to close the dialog box if the user doesnt pick a
file.I thought "Cancel" would just make it go away, but noooo.I will
need "filename" for the next operation if they choose one.
Help Please

OpenFileDialog opnFile = new OpenFileDialog();
opnFile.Filter = "txt files (*.txt)|*.txt|All files
(*.*)|*.*";
opnFile.ShowDialog();
filename = opnFile.FileName;
// StreamReader openReader = new
StreamReader(openStream);
textBox4.Text = File.ReadAllText(opnFile.FileName);
this.button3.Enabled = true;

Thanks
Mike
 
Hi Mike,

First of all, the ShowDialog() method of a
System.Winodws.Forms.OpenFileDialog class
(http://msdn2.microsoft.com/en-us/library/system.windows.forms.openfiledialog.aspx)
returns a System.Windows.Forms.DialogResult
(http://msdn2.microsoft.com/en-us/library/system.windows.forms.dialogresult.aspx)
enumeration value, which indicates the action that the user took, such as
clicking the OK or Cancel buttons in the dialog box.

Second, it is very important to take note of any class which implements a
Dispose method, and ensure that it is properly Disposed. Otherwise, memory
leaks are likely to occur.

Here is an example, using a "using block" to ensure that the object is
Disposed, and accounting for the DialogResult returned:

using (OpenFileDialog opnFile = new OpenFileDialog())
{
opnFile.Filter = "txt files (*.txt)|*.txt|All files(*.*)|*.*";
if (opnFile.ShowDialog() == DialogResult.OK)
{
filename = opnFile.FileName;
// etc.
}
}

--
HTH,

Kevin Spencer
Microsoft MVP
Software Composer
http://unclechutney.blogspot.com

A watched clock never boils.
 
Back
Top