当您FormatException
尝试将无法转换为 struct 类型的字符串转换int
为int
. 在进行转换之前,您可以随时int.TryParse(string s, out int result)
查看是否string
能够进行int
转换。
例子
private void textBox1_TextChanged(object sender, EventArgs e)
{
int x = 0; //Initialize a new int of name x and set its value to 0
if (int.TryParse(textBox1.Text, out x)) //Check if textBox1.Text is a valid int
{
int vlera1 = Convert.ToInt32(textBox1.Text); //Initialize a new int of name vlera2 and set its value to (textBox1.Text as int)
}
else
{
//DoSomething if required
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
int x = 0; //Initialize a new int of name x and set its value to 0
if (int.TryParse(textBox2.Text, out x)) //Check if textBox2.Text is a valid int
{
int vlera2 = Convert.ToInt32(textBox2.Text); //Initialize a new int of name vlera2 and set its value to (textBox1.Text as int)
}
else
{
//DoSomething if required
}
}
另一种解决方案
您可能总是使用 try-catch 语句来查看您提供的代码是否引发了异常,并在需要时执行某些操作
例子
private void textBox1_TextChanged(object sender, EventArgs e)
{
try
{
int vlera1 = Convert.ToInt32(textBox1.Text); //Initialize a new int of name vlera2 and set its value to (textBox1.Text as int)
}
catch (Exception EX)
{
MessageBox.Show(EX.Message); //(not required) Show the message from the exception in a MessageBox
}
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
try
{
int vlera2 = Convert.ToInt32(textBox2.Text); //Initialize a new int of name vlera2 and set its value to (textBox1.Text as int)
}
catch (Exception EX)
{
MessageBox.Show(EX.Message); //(not required) Show the message from the exception in a MessageBox
}
}
注意:try-catch 语句由一个 try 块和一个或多个 catch 子句组成,这些子句为不同的异常指定处理程序
谢谢,
我希望你觉得这有帮助:)