按退格键时出现 FormatException

FormatException when pressing backspace

这段代码将十六进制值从输入转换为十进制,并将其放入另一个文本框。当您在空文本框中按退格键时,会抛出一个 FormatException,并指向这一行:

int decValue = int.Parse(textBox3.Text, System.Globalization.NumberStyles.HexNumber);

完整处理程序:

private void textBox3_TextChanged(object sender, EventArgs e)
{
    if (textBox3.Focused == true)
    {
        int decValue = int.Parse(textBox3.Text, System.Globalization.NumberStyles.HexNumber);
        string decimalnumber = Convert.ToString(decValue, 10);
        string binary = Convert.ToString(decValue, 2);
        textBox1.Text = decimalnumber;
        textBox2.Text = binary;
    }
}

您必须像这样添加一个空支票:

private void textBox3_TextChanged(object sender, EventArgs e)
{
    if (textBox3.Focused == true)
    {
        if (string.IsNullOrEmpty(textBox3.Text))
        {
            textBox1.Text = "";
            textBox2.Text = "";
        }
        else
        {
            int decValue = int.Parse(textBox3.Text, System.Globalization.NumberStyles.HexNumber);
            string decimalnumber = Convert.ToString(decValue, 10);
            string binary = Convert.ToString(decValue, 2);
            textBox1.Text = decimalnumber;
            textBox2.Text = binary;
        }
    }
}

我建议使用 TryParse 检查用户是否输入了非十六进制字符,例如特殊字符。

int decValue = 0;
if (int.TryParse(textBox3.Text, System.Globalization.NumberStyles.HexNumber, null, out decValue))
{
    string decimalnumber = Convert.ToString(decValue, 10);
    string binary = Convert.ToString(decValue, 2);
    textBox1.Text = decimalnumber;
    textBox2.Text = binary;
}

FormatException 表示输入字符串的格式不适合所选样式。我猜你的情况是空字符串引起的。

您可以检查空字符串值

if (textBox3.Focused == true && !string.IsNullOrEmpty(textBox3.Text)) {
    ...
}

或者您可以使用 int.TryParse

int decValue;
if(int.TryParse(textBox3.Text, NumberStyles.HexNumber, null, out decValue)) {
    ...
}