0

Possible Duplicate:
How can I convert String to Int?

I have a textbox that the user can put numbers in, is there a way to convert it to int? As I want to insert it into a database field that only accepts int.

The tryParse method doesn't seem to work, still throws exception.

Community
  • 1
  • 1
6TTW014
  • 627
  • 2
  • 11
  • 24

6 Answers6

10

Either use Int32.Parse or Int32.TryParse or you could use System.Convert.ToInt32

int intValue = 0;
if(!Int32.TryParse(yourTextBox.Text, out intValue))
{
    // handle the situation when the value in the text box couldn't be converted to int
}

The difference between Parse and TryParse is pretty obvious. The latter gracefully fails while the other will throw an exception if it can't parse the string into an integer. But the differences between Int32.Parse and System.Convert.ToInt32 are more subtle and generally have to do with culture-specific parsing issues. Basically how negative numbers and fractional and thousands separators are interpreted.

Mike Dinescu
  • 54,171
  • 16
  • 118
  • 151
2
int temp;

if (int.TryParse(TextBox1.Text, out temp))
   // Good to go
else
   // display an error
RQDQ
  • 15,461
  • 2
  • 32
  • 59
1

You can use Int32.Parse(myTextBox.text)

Shlomo Zalman Heigh
  • 3,968
  • 8
  • 41
  • 71
1

If this is WinForms, you can use a NumericUpDown control. If this is webforms, I'd use the Int32.TryParse method along with a client-side numeric filter on the input box.

Mike Cole
  • 14,474
  • 28
  • 114
  • 194
1
int orderID = 0;

orderID = Int32.Parse(txtOrderID.Text);
Bastardo
  • 4,144
  • 9
  • 41
  • 60
0
private void txtAnswer_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (bNumeric && e.KeyChar > 31 && (e.KeyChar < '0' || e.KeyChar > '9'))
        {
            e.Handled = true;
        }
    }

Source: http://www.monkeycancode.com/c-force-textbox-to-only-enter-number

nashcheez
  • 5,067
  • 1
  • 27
  • 53
Bastardo
  • 4,144
  • 9
  • 41
  • 60