我有一个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;
}
}
有没有办法解决这个问题?我不想硬编码.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这样的值。
我将如何比较哪个TextBox没有KeyPress硬编码作为语句.Name中的字符串?case