在 TextBox 中,我正在监视文本更改。在做一些事情之前,我需要检查文本。但我现在只能检查旧文本。我怎样才能得到新的文本?
private void textChanged(object sender, EventArgs e)
{
// need to check the new text
}
我知道 .NET Framework 4.5 有新TextChangedEventArgs
类,但我必须使用 .NET Framework 2.0。
获取新值
您可以只使用Text
. TextBox
如果此事件用于多个文本框,那么您将需要使用该sender
参数来获得正确的TextBox
控件,就像这样......
private void textChanged(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
if(textBox != null)
{
string theText = textBox.Text;
}
}
获取旧值
对于那些希望获得旧值的人,您需要自己跟踪。我建议一个简单的变量,它以空开头,并在每个事件结束时更改:
string oldValue = "";
private void textChanged(object sender, EventArgs e)
{
TextBox textBox = sender as TextBox;
if(textBox != null)
{
string theText = textBox.Text;
// Do something with OLD value here.
// Finally, update the old value ready for next time.
oldValue = theText;
}
}
如果您打算大量使用它,您可以创建自己的继承自内置控件的 TextBox 控件,并添加此附加功能。
即使使用较旧的 .net fw 2.0,如果不在 textbox.text 属性本身中,您仍然应该在 eventArgs 中拥有新旧值,因为事件是在文本更改之后而不是在文本更改期间触发的。
如果您想在更改文本时执行某些操作,请尝试 KeyUp 事件而不是 Changed。
private void stIDTextBox_TextChanged(object sender, EventArgs e)
{
if (stIDTextBox.TextLength == 6)
{
studentId = stIDTextBox.Text; // Here studentId is a variable.
// this process is used to read textbox value automatically.
// In this case I can read textbox until the char or digit equal to 6.
}
}