Search code examples
c#winformstextfieldonchange

Getting a value before it is changed


I am having trouble with getting a value in a text box before the value is changed either by user input or programmatically.

I figure it has to do with the _TextChanged event but once this executes how do I get the old value which was already there before the change?

For example number 3 is in the text field. The number then changes to 4 how do I save 3?

Thanks in advance!


Solution

  • Do not store anything in the TextBox. Use it only to display/edit value.

    private string value;
    
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        // at this moment value is still old
        var oldValue = value;
        value = ((TextBox)sender).Text; // text1.Text
    
        // here you have oldValue and new value
    }
    

    Maybe you don't want to update value after each TextChanged. Maybe you will do it when form is closed, some button is pressed, etc.

    Anyhow idea should be clear: if you need to have old value, then store it somewhere yourself (as a variable, as a Tag, as application setting, exporting, etc.).

    Also, take care about how user will work. If TextBox contains 3, then user may first press 4 and only then delete 3. Or user may accidentally press 54. Which of those will be old value: 3, 34, 54 ? Simply to demonstrate you, what there could be consequent problems to having concept of old value. Mayhaps you don't want it and there is better solution to what you are trying to solve by getting old value.