如何在TextChanged中获取新文本?
在TextBox中,我正在监视文本更改。 在做一些事情之前我需要检查文本。 但我现在只能检查旧文本。 我怎样才能获得新文本?
private void textChanged(object sender, EventArgs e) { // need to check the new text }
我知道.NET Framework 4.5有新的TextChangedEventArgs
类,但我必须使用.NET Framework 2.0。
获得新价值
您可以只使用TextBox
的Text
属性。 如果此事件用于多个文本框,那么您将需要使用sender
参数来获取正确的TextBox
控件,如下所示…
private void textChanged(object sender, EventArgs e) { TextBox textBox = sender as TextBox; if(textBox != null) { string theText = textBox.Text; } }
获得OLD值
对于那些希望获得旧价值的人,您需要自己跟踪。 我建议一个简单的变量开始为空,并在每个事件结束时更改:
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控件,该控件inheritance自内置控件,并添加此附加function,如果您打算大量使用它。
看看文本框事件 ,如KeyUp ,KeyPress等。例如:
private void textbox_KeyUp(object sender, KeyEventArgs e) { // Do whatever you need. }
也许这些可以帮助您实现您正在寻找的东西。
即使使用较旧的.net fw 2.0,如果不在textbox.text属性中,你仍然应该在eventArgs中拥有新旧值,因为事件是在文本更改之后而不是在文本更改期间触发的。
如果您想在更改文本时执行操作,请尝试KeyUp事件,而不是更改。
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. } }