How to get the NEW text in TextChanged?

瘦欲@ 提交于 2019-12-22 02:20:31

问题


In a TextBox I'm monitoring the text changes. I need to check the text before doing some stuff. But I can only check the old text in the moment. How can I get the new Text ?

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

I know .NET Framework 4.5 has the new TextChangedEventArgs class but I have to use .NET Framework 2.0.


回答1:


Getting the NEW value

You can just use the Text property of the TextBox. If this event is used for multiple text boxes then you will want to use the sender parameter to get the correct TextBox control, like so...

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

Getting the OLD value

For those looking to get the old value, you will need to keep track of that yourself. I would suggest a simple variable that starts out as empty, and changes at the end of each event:

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;
    }
}

You could create your own TextBox control that inherits from the built-in one, and adds this additional functionality, if you plan to use this a lot.




回答2:


Have a look at the textbox events such as KeyUp, KeyPress etc. For example:

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

Maybe these can help you achieve what you're looking for.




回答3:


Even with the older .net fw 2.0 you should still have the new and old value in the eventArgs if not in the textbox.text property itself since the event is fired after and not during the text changing.

If you want to do stuff while the text is being changed then try the KeyUp event rather then the Changed.




回答4:


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.
    }
}


来源:https://stackoverflow.com/questions/14337057/how-to-get-the-new-text-in-textchanged

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!