FormatException
型の構造体に変換できない文字列を に変換しようとすると、 が返さ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 ブロックとそれに続く 1 つ以上の catch 句で構成され、さまざまな例外のハンドラーを指定します。
ありがとう、
これがお役に立てば幸いです:)