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.

0

6 Answers 6

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.

Sign up to request clarification or add additional context in comments.

Comments

2
int temp; if (int.TryParse(TextBox1.Text, out temp)) // Good to go else // display an error 

Comments

1

You can use Int32.Parse(myTextBox.text)

Comments

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.

Comments

1
int orderID = 0; orderID = Int32.Parse(txtOrderID.Text); 

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.