c# forcing a numeric updown to only accept positive integers with try-parse

Jamaul Smith picture Jamaul Smith · Oct 4, 2012 · Viewed 7.1k times · Source

I've only been doing this a few days and I'm pretty confused.

Everything else works fine, and the box only displays integers, but it still calculates with decimal values.

Answer

Adam Plocher picture Adam Plocher · Oct 4, 2012

You should be able to do a int myInt = Convert.ToInt32(numBox.Value);

numBox.Value is a decimal, but that code will cause it to get converted to an integer.

Just know that IF you do get a decimal value back, it will round it up or down.

EDIT: Aghilas Yakoub's solution might be better if you want only positive values. My solution will convert the decimal to an int, but it could still allow for negatives. Really what you should do is set your numBox.Minimum to 0 so it can't go below 0.

EDIT 2: If you want to warn when the value is negative, try this:

int myInt = Convert.ToInt32(numBox.Value);
if (myInt < 0)
{
    MessageBox.Show("Warning, your number must be 0 or greater");
}

Do you want to warn if the value isn't a whole number (has decimal values)?