我有一个 KeyPress
绑定(bind)在多个 TextBox
上的事件s 和我想检查哪个 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;
}
}
有没有办法解决这个问题?我不想硬编码 .Name
作为string
以防 future 的开发人员致力于此。
我可以这样做吗,否则它会成为运行时错误吗?
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
这样的值(value)观。
我如何比较哪个 TextBox
有一个 KeyPress
无需对 .Name
进行硬编码作为 case
中的字符串声明?
最佳答案
你不能那样使用开关
。 case
需要是编译时常量。
你可以这样做:
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) { ... }
}
但是恕我直言,最好的解决方案是使用两个更改回调,每个方法一个。那么您就不需要比较 textbox
es 或 textbox
的名称。
因此您可以将 UpdateValues
更改为一个 UpdateUserName
和 UpdatedPasswort
。这样做,方法名称将清楚地表明该方法做什么(或至少应该做什么),使您的代码更具可读性。
关于c# - 按名称属性比较文本框控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51618357/