conversion problem
how can I convert a string from a textbox into a long or an int ??
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Jan MontanoPosted Jun 6, 2007, 9:30 PM
Posted Jun 6, 2007, 12:08 PM
Hello,
I just manually color and space everything around. If you have Visual Studio and you copy and paste code from there, itll automatically color it all correctly for you but the curly braces and everything will need to be readjusted as it aligns everything to the left.
Jan MontanoPosted Jun 6, 2007, 6:23 AM
I don't know how to pm you so I'll post my concern here instead. I noticed that your post is formatted in a nice way. Are you using a tool or editor for it? Normally, I would manually add html tags on my post just for it to be readable especially if it's code I'm posting. But if there's a better, and faster way, that would greatly help. Please advise. Thanks.
Posted Jun 5, 2007, 4:33 PM
Int16 intTextBoxInteger;
try //Try to convert the contents of textBox1 to an integer
{
intTextBoxInteger = Convert.ToInt16(textBox1.Text);
}
catch //If textBox1 cannot be converted, catch it and throw a programmer defined error message
{
MessageBox.Show("Please input a number.", "Help", MessageBoxButtons.OK,
MessageBoxIcon.Information);
textBox1.Focus();
textBox1.SelectAll();
}
I always like to put out examples, I know I like to see examples of the code with comments on how it works, lol.
AlanPosted Jun 5, 2007, 3:15 PM
For .NET 1.0 or 1.1, you can achieve something similar by placing the call to the Convert method in a try/catch statement.
Posted Jun 5, 2007, 1:30 PM
Just be careful because if you are converting a string to an integer and the string just happens to be alphabetic, such as converting "A" to an integer, the program will crash because obviously "A" is not an cannot be converted to a numeric data type. Try this to prevent that:
bool boolIsIntConverted; //Declare true/false check variable
Int16 intTextBoxInteger;
boolIsIntConverted = Int16.TryParse(textBox1.Text, out intTextBoxInteger);
if (!boolIsIntConverted) //If text box input was not converted
{
MessageBox.Show("Please input a number.", "Help", MessageBoxButtons.OK, MessageBoxIcon.Information);
textBox1.Focus();
textBox1.SelectAll();
}
else //If it was converted, all is well. Return to class
{
return;
}
Im writing this code while Im at work so I have nothing to test it on so I am not positive it will work off hand without actually testing it, but Im pretty sure it should work, lol. Ill check it when I get home and make sure and Ill add any edits necessary to make it correct.
Adace Gavril MariusPosted Jun 4, 2007, 9:30 AM
AlanPosted Jun 4, 2007, 9:08 AM
Try:
long num64 = System.Convert.ToInt64(textBox1.Text);
or
int num32 = System.Convert.ToInt32(textBox1.Text);