C# Need Help on Converting String to Int?
So... I have this section of code here, everything seems perfect but when I try to run this, it gives a formatting exception handler error.
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (textBox1.Text != null)
{
minusTime = Convert.ToInt32(textBox1.Text); // fix this... idk what's even wrong. Just trying to assign user input to minusTime...
}
else
{
minusTime = 0;
}
}
*Note: 开发者_JAVA百科textbox1 is user input of an integer value. minusTime is a null integer that is to be assigned to the user input.
I've tried running this with just "Convert.ToInt32(textBox1.Text)" but it still gives me an exception saying the user inputted a wrong format... when the user input is clearly an int.
You want
bool result = Int32.TryParse(textBox1.Text, out minusTime);
This will cope if the input isn't an integer returning false
.
MSDN page
There is another overload that takes in more information about the possible format of the number:
public static bool TryParse(
string s,
NumberStyles style,
IFormatProvider provider,
out int result
)
This will cope with currency symbols etc.
Try using:
minusTime = Int32.Parse(textBox1.Text);
private void textBox1_TextChanged(object sender, EventArgs e)
{
var minusTime;
if (textBox1.Text != null && int.TryParse(textBox1.Text, out minusTime))
{
}
else
{
minusTime = 0;
}
}
You can use:
int minusTime=0;
Int32.TryParse(textBox1.Text, out minusTime);
minusTime will be 0 if textBox1.Text is not integer or even if it is null.
精彩评论