private void button1_Click(object sender, EventArgs e)
{
long i = Int64.Parse(textBox1.Text);
MessageBox.Show(i.ToString());
}
In This code, If we pass the textBox value in interger type, It's return integer value just like
textBox1.text=23 return 23.
But if we enter string type value in textBox, it's fire exception, as like
textBox1.text="Tom".
Why?
Loading
VulpesPosted Aug 27, 2012, 11:38 AM
A good way to test for invalid values is to use Int64.TryParse rather than Int64.Parse. The former never throws an exception but returns true if it can be converted or false otherwise. You also pass a variable to it (as an 'out' parameter) which is filled with the value if the conversion is successful or 0 otherwise.
So you could replace your original code with something like this:
tom linkerPosted Aug 28, 2012, 10:49 AM
VulpesPosted Aug 28, 2012, 9:12 AM
If you're asking whether Int32.Parse or Int64.Parse are any use at all, then the answer is 'yes' if you're certain beforehand that the string you're parsing represents an integer which is within the appropriate range.
This isn't normally possible with TextBoxes because, even if you have another event handler which ensures that only digits are entered, the result may still be out of range or the user may leave it empty or paste in some non-numeric stuff.
So, for robust programming, you'd have to use them in conjunction with a try/catch statement but that's in effect what the TryParse methods are doing anyway.
tom linkerPosted Aug 28, 2012, 6:51 AM
If we can't use Int32,Int64 for change TextBox(String) value. what can we use in it?
tom linkerPosted Aug 27, 2012, 11:23 AM
{
long i = Int64.Parse(textBox1.Text);
MessageBox.Show(i.ToString());
}
In This Code, we pass the string in textBox. it's fire exception why?
please clear my confusion.
VulpesPosted Aug 27, 2012, 11:16 AM
If it can, then it makes the conversion and returns an Int32 (or 'int' in C#) with that value.
If it cannot, then it throws one of three exceptions:
1. An ArgumentNullException if the string is null.
2. A FormatException if it doesn't represent an integer of any size.
3. An OverflowException if it does represent an integer but it's too big or too small to fit into an Int32.
tom linkerPosted Aug 27, 2012, 11:01 AM
What is the working of Int32.parse() method?
R ACHUTHAPosted Aug 27, 2012, 10:38 AM
long i=Int64.Parse(textBox1.Text);
means your trying to convert the text box text to integer and save it into i. It is working for the textbox contains numeric data.
If the text box contains the alphabets or alphanumeric value then it will get exception because we con't convert the string data to integer value.