21

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

private void textChanged(object sender, EventArgs e)
{
    // need to check the new text
}

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

4

4 回答 4

20

获取新值

您可以只使用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 控件,并添加此附加功能。

于 2013-01-15T11:57:36.327 回答
2

查看文本框事件,例如KeyUp、 KeyPress 等。例如:

private void textbox_KeyUp(object sender, KeyEventArgs e)
{
    // Do whatever you need.
}

也许这些可以帮助您实现您正在寻找的东西。

于 2013-01-15T11:52:26.567 回答
0

即使使用较旧的 .net fw 2.0,如果不在 textbox.text 属性本身中,您仍然应该在 eventArgs 中拥有新旧值,因为事件是在文本更改之后而不是在文本更改期间触发的。

如果您想在更改文本时执行某些操作,请尝试 KeyUp 事件而不是 Changed。

于 2013-01-15T11:54:27.343 回答
-1
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.
    }
}
于 2016-04-16T10:50:22.553 回答