如何在TextBox的文本更改事件中使用IF语句

时间:2015-01-23 15:00:13

标签: c#

private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (a.Equals(b))
    {
        result = a.ToString();
        textBox1.Text = result;
        textBox1.TextAlign = HorizontalAlignment.Left;
    }
    else
        result = b.ToString();
    textBox1.Text = result;
    textBox1.TextAlign = HorizontalAlignment.Center;
}

1 个答案:

答案 0 :(得分:0)

很可能你忘记在else语句中添加括号。

试试这段代码:

private void textBox1_TextChanged(object sender, EventArgs e)
{
    if (a.Equals(b))
    {
        result = a.ToString();
        textBox1.Text = result;
        textBox1.TextAlign = HorizontalAlignment.Left;
    }
    else
    {
        result = b.ToString();
        textBox1.Text = result;
        textBox1.TextAlign = HorizontalAlignment.Center;
    }
}

将大括号放在ifelse语句,loops等中始终是一种好习惯。

阅读此问题的答案:Why is it considered a bad practice to omit curly braces?