65.9K
CodeProject is changing. Read more.
Home

InputBox: A simple user input dialog

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Dec 1, 2011

CPOL
viewsIcon

11726

Consider the scenario where the input value must be valid.public static double? GetDouble(string caption, string defaultValue, bool mustBeValid = false){ ClearLastError(); using (InputForm inForm = new InputForm(caption, defaultValue)) { while (true) { ...

Consider the scenario where the input value must be valid.

public static double? GetDouble(string caption, string defaultValue, bool mustBeValid = false)
{
   ClearLastError();
   using (InputForm inForm = new InputForm(caption, defaultValue))
   {
       while (true)
       {
          if (inForm.ShowDialog() != DialogResult.Cancel)
          {
             if (inForm.StringValue != string.Empty)
             {
                try 
                { 
                    //If valid value, we will break the loop.
                    return double.Parse(inForm.StringValue); 
                }
                catch (Exception ex)
                {
                  LastError = ex;
                }
             }
          }
          if(mustBeValid)
          {
             MessageBox.Show("You must enter a valid value");
          } else
          {
             return null;
          }
      }
   }
}