【问题标题】:Compare TextBox Controls by Name property按名称属性比较文本框控件
【发布时间】:2018-07-31 16:47:30
【问题描述】:

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

我正在尝试根据文本框的.Name 属性比较哪个TextBox 被点击。我在 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;
    }
}

有没有办法解决这个问题?我不想将.Name 硬编码为string,以防将来的开发人员对此进行处理。

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

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 值。

如果不将.Name 硬编码为case 语句中的字符串,我如何比较哪个TextBox 具有KeyPress

【问题讨论】:

  • 你试过了吗?
  • 不,你不能这样做,常量值必须从编译时常量派生。不确定在不遍历表单的所有控件的情况下执行您所要求的有效方法。这不会很有效。编辑。看到我的回答,我意识到如果你愿意使用开关,那么 if/elseif 模式也可以工作
  • 如果您想根据文本框执行不同的操作,为什么要将相同的事件处理程序连接到多个文本框?您可能会考虑将功能分解为一两个方法,然后将不同的事件处理程序连接到需要不同功能的控件,并在适当的情况下调用常用方法。

标签: c# wpf winforms


【解决方案1】:

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

你可以这样做:

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

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

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

另一种方法是使用作为发件人的文本框参考:

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

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

但恕我直言,最好的解决方案是使用两个更改回调,每个方法一个。那么您不需要比较textboxes 或textbox 的名称。

因此您可以将UpdateValues 更改为UpdateUserNameUpdatedPasswort。这样做,方法名称将清楚地显示,方法做什么(或至少应该做什么),使您的代码更具可读性。

【讨论】:

  • 演员表是不必要的 - 你可以做if (sender == textBox1)
  • @RufusL 你是对的,我只是假设需要访问 if-body 中的文本框,因此我包括了演员表。
  • 当然,这是有道理的!尽管他们确实可以通过使用 == 运算符右侧的那个来访问文本框。没什么大不了的,只是节省一些打字和一点点内存的提示。
【解决方案2】:

试试这个

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-02
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    相关资源
    最近更新 更多