简体   繁体   中英

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!

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.

Why not save the current value in the textbox in a variable during the textchanged event. That way, it is the "previous" value when the event is fired again.

You can save the value of textbox in some variable. For example string currentVal = txtName.Text;

string currentVal can be used as a previous value in text_changed event.

Have you tried making a timer. Every tick you write the input to a string. If the input of the textbox is not equal to the content in the string, you trigger what you wanted to do. That way you can trigger a void with the old input.

private string oldInput;

....

void TimerTick(Object source, ElapsedEventArgs e)
{
    if (oldInput != MyTextBox.Text) MyVoid(oldInput);
    oldInput = MyTextBox.Text;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM