Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the NEW text in TextChanged?

Tags:

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.

like image 960
Bitterblue Avatar asked Jan 15 '13 11:01

Bitterblue


People also ask

How does TextChanged work?

The TextChanged event is raised when the content of the text box changes between posts to the server. The event is only raised if the text is changed by the user; the event is not raised if the text is changed programmatically.

Which event is generated when TextBox text is changed?

The event handler is called whenever the contents of the TextBox control are changed, either by a user or programmatically. This event fires when the TextBox control is created and initially populated with text.

What event's for a TextBox can determine when the text inside the control has been modified?

To see all changes to the text in a TextBox, you can handle the TextChanged event. This event fires after the text has changed. In the TextChanged event, the easiest way to inspect the text being entered is to just look at the value of the Text property.


Video Answer


1 Answers

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.

like image 189
musefan Avatar answered Oct 11 '22 03:10

musefan