如何在TextChanged中获取新文本?

Bit*_*lue 18 c# events text textbox

在TextBox中,我正在监视文本更改.在做一些事情之前我需要检查文本.但我现在只能检查旧文本.我怎样才能获得新文本?

private void textChanged(object sender, EventArgs e)
{
    // need to check the new text
}
Run Code Online (Sandbox Code Playgroud)

我知道.NET Framework 4.5有新TextChangedEventArgs类,但我必须使用.NET Framework 2.0.

mus*_*fan 16

获得新价值

你可以使用的Text属性TextBox.如果此事件用于多个文本框,那么您将需要使用该sender参数来获取正确的TextBox控件,如此...

private void textChanged(object sender, EventArgs e)
{
    TextBox textBox = sender as TextBox;
    if(textBox != null)
    {
        string theText = textBox.Text;
    }
}
Run Code Online (Sandbox Code Playgroud)

获得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;
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以创建自己的TextBox控件,该控件继承自内置控件,并添加此附加功能,如果您打算大量使用它.

  • 我刚才发誓,我在这次活动中只看过旧版本的文字.现在文本在事件之前被更改.所以问题现在是多余的. (5认同)