2

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.

Jamaul Smith
  • 53
  • 1
  • 6

3 Answers3

2

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)?

Adam Plocher
  • 13,994
  • 6
  • 46
  • 79
0

You can try with

UInt32 result = 0;

UInt32.TryParse("...",
                new CultureInfo(""),
                out result);

if(result == 0)
{
  Console.WriteLine("No parsing");
}
else
{
 Console.WriteLine("result={0}", result);
}
Aghilas Yakoub
  • 28,516
  • 5
  • 46
  • 51
  • Sorry, I'm so noob, but how can I define CultureInfo since it says it isn't used. And is there a way I can convert this to a warning message, messagebox.show("") instead of just rounding? – Jamaul Smith Oct 04 '12 at 21:04
-1

A more elegant solution would be:

If you have access to DevExpress controls, you should use a SpinEdit control. To limit its range from 0 to 999 (only integer number) set its:

  • Properties.Mask.EditMask to "##0;"
  • Properties.MaxValue to 999

Then the following line should work well without exceptions:

int myInt = Convert.ToInt32(numBox.Value);
Szabolcs Antal
  • 877
  • 4
  • 15
  • 27