按退格键时格式异常

时间:2015-10-25 22:11:01

标签: c# exception format

此代码片段将HEX值从输入转换为十进制,并将其放入另一个文本框。当您在空文本框中按退格键时,会抛出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;
    }
}

2 个答案:

答案 0 :(得分:1)

FormatException表示输入字符串的格式不正确。在你的情况下,我猜,问题是由空字符串引起的。

您可以检查空字符串值

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

或者您可以使用int.TryParse

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

答案 1 :(得分:0)

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

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;
}