1

我有一个KeyPress绑定在多个TextBoxs 上的事件,我想检查哪个TextBox被点击并根据点击的那个做不同的事情。

我正在尝试根据文本框的属性比较哪个TextBox被点击。.Name我在 switch 语句中执行此操作,但正在获取a Constant value is expected.

private void UpdateValues(object sender, KeyPressEventArgs e)
{
    TextBox textBox = (TextBox)sender;

    switch (textBox.Name)
    {
        case txtBox1.Name: // Error here
            break;
    }
}

有没有办法解决这个问题?我不想硬编码.Namestring以防未来的开发人员在这方面工作。

我可以这样做,还是会成为运行时错误?

private const string _TXTBOX1NAME = txtBox1.Name;


private void UpdateValues(object sender, KeyPressEventArgs e)
{
    TextBox textBox = (TextBox)sender;

    switch (textBox.Name)
    {
        case _TXTBOX1NAME: // Use the const variable
            break;
    }
}

编辑:

实际上,您不能分配const这样的值。

我将如何比较哪个TextBox没有KeyPress硬编码作为语句.Name中的字符串?case

4

2 回答 2

2

你不能这样使用switchcases 需要是编译时常量。

你可以这样做:

private void UpdateValues(object sender, KeyPressEventArgs e)
{
    TextBox textBox = (TextBox)sender;

    switch (textBox.Name)
    {
        case "NameTextBox": 
            break;
        case "PasswordTextBox":
            break;
    }
}

如果你知道名字,这是可能的。您的示例失败,因为textbox1.Name不是常量,而是从 one 的实例读取的属性TextBox

另一种方法是使用作为发件人给出的文本框引用:

private void UpdateValues(object sender, KeyPressEventArgs e)
{
    TextBox textBox = (TextBox)sender;

    if(textBox == textBox1) { ... }
    if(textBox == textBox2) { ... }
}

但恕我直言,最好的解决方案是使用两个更改回调,每个方法一个。然后你不需要比较textboxes 或textbox's 的名字。

所以你可以UpdateValues变成一个UpdateUserNameand UpdatedPasswort。这样做,方法名称将清楚地显示该方法做什么(或至少应该做什么),使您的代码更具可读性。

于 2018-07-31T16:55:59.437 回答
1

尝试这个

private void UpdateValues(object sender, KeyPressEventArgs e)
{
    TextBox textBox = (TextBox)sender;

    if (textBox.Name == textBox1.Name){
          //error
    } else if(textBox.Name == textBox2.Name){
          // and so on
    }
}
于 2018-07-31T16:55:44.377 回答