65.9K
CodeProject is changing. Read more.
Home

InputBox: A simple user input dialog

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Dec 1, 2011

CPOL
viewsIcon

5750

So here is a tip on how to improve upon this code. Do not silently catch exceptions! Instead, create a very simple logging mechanism that allows you to inspect the exception, either from code or during debugging.public static class InputBox{ public static Exception LastError {get; private...

So here is a tip on how to improve upon this code. Do not silently catch exceptions! Instead, create a very simple logging mechanism that allows you to inspect the exception, either from code or during debugging.

public static class InputBox
{
  public static Exception LastError {get; private set;}
  public static void ClearLastError(){ LastError = null;}

  public static double? GetDouble(string caption, string defaultValue)
  {
     ClearLastError();
     using (InputForm inForm = new InputForm(caption, defaultValue))
     {
            if (inForm.ShowDialog() == DialogResult.Cancel) return null;
            if (inForm.StringValue == string.Empty) return null;
            try { return double.Parse(inForm.StringValue); }
            catch (Exception ex)
            { 
               LastError = ex;
               return null; 
            }
     }
  }  
}

Contrived usage:

double? value = InputBox.GetDouble("xyz", "1.0");
if(!value.HasValue && InputBox.LastError is OutOfMemoryException)
{
    // holy ship, batman!
}