Share via


Storing Value of Text Box to int Variable in Windows Form

Question

Thursday, October 8, 2009 5:11 PM

I want this text box to be numerical values only, and I want it to store the value that is typed into it.

I tried an Int32.Parse of the text box, but that didn't work.

How can I do this?

I'm using Visual Studio 2008 with C#.

I'd greatly appreciate it.

-Zach

All replies (4)

Thursday, October 8, 2009 5:27 PM âś…Answered

You will need to do

     int value = Int32.Parse(textBox.Text );

However, if the user types "a" into the text box, it'll raise an exception.  It might be better to put error handling in here:

     int value;
     if (!Int32.TryParse(textBox.Text, out value))
     {
         // The text box isn't a valid number - tell the user!
         MessageBox.Show("Please enter a valid number!");
     }
Reed Copsey, Jr. - http://reedcopsey.com


Thursday, October 8, 2009 5:21 PM

Did you try using the toString() method?


Thursday, October 8, 2009 5:30 PM

Thank you very much sir. I wouldn't have remembered to do the error handling either.


Saturday, May 21, 2011 1:17 PM

when i tried int a=int.parse(textbox1.text)

it shows an exception

input string was not in correct methos

 

well i can handle this exception but want to know why thi error occurs

sunil dhanerwal