2

So I'm trying to create a validating event that makes sure a textbox isn't empty and that the number entered doesn't exceed 2000. I've posted what I have but every time I run it I get a message that the exception wasn't handled because the "kwh = decimal.Parse(khtextBox.Text)" input is not in the correct format. The way I have it, the validating works if the number exceeds 2000, but not if the textbox is blank. What am I doing wrong? Also new to programming so please explain like you're talking to a 3 year old! Thanks :)

private void khtextBox1_Validating(object sender, CancelEventArgs e)
{
        decimal kwh;
        kwh = decimal.Parse(khtextBox1.Text);
        bool blank = false;

        if (blank)
        {
            MessageBox.Show("Please enter a valid number.");
        }

        if (kwh > 2000)
        {
            MessageBox.Show("Kilowatt-Hours cannot exceed 2000.");
            e.Cancel = true;
        }
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
rachelabr
  • 53
  • 1
  • 3
  • Either `return` after the first `if` or replace `if (kwh > 2000)` with `else if (kwh > 2000)` This should solve your problem. – Alex Barac Sep 13 '14 at 19:35

2 Answers2

3

Try using the decimal.TryParse method, which try to convert the string to a decimal and returns a bool value if the conversion succeed, for sample:

decimal kwh;
if (!decimal.TryParse(khtextBox1.Text, out kwh)) // check if the conversion has failed
{
   MessageBox.Show("Please enter a valid number.");
   e.Cancel = true;
}
else // conversion ok, you can use the kwh value
{    
   if (kwh > 2000)
   {
      MessageBox.Show("Kilowatt-Hours cannot exceed 2000.");
      e.Cancel = true;
   }
}
Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
0

You clearly mention yourself what the issue is. The input has to be something that could be converted to decimal some number.

It seems like an issue with incorrect input. Could you try using TryParse instead or you could simply change that second 'if' block to 'else if'.

decimal outputKWH;
kwh = decimal.TryParse(khtextBox.Text, out outputKWH)
haku
  • 4,105
  • 7
  • 38
  • 63