简体   繁体   English

在更改之前获取值

[英]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? 我认为它与_TextChanged事件有关,但是一旦执行此操作,我如何获得更改之前已存在的旧值?

For example number 3 is in the text field. 例如,数字3在文本字段中。 The number then changes to 4 how do I save 3 ? 然后数字变为4如何保存3

Thanks in advance! 提前致谢!

Do not store anything in the TextBox . 不要在TextBox存储任何内容。 Use it only to display/edit value . 仅用于显示/编辑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 . 也许你不想在每次TextChanged后更新value 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.). 无论如何,想法应该是明确的:如果你需要有旧的价值,那么你自己将它存储在某个地方(作为变量,作为Tag ,作为应用程序设置,导出等)。

Also, take care about how user will work. 另外,请注意用户的工作方式。 If TextBox contains 3 , then user may first press 4 and only then delete 3 . 如果TextBox包含3 ,则用户可以先按4然后再删除3 Or user may accidentally press 54 . 或者用户可能会意外按54 Which of those will be old value: 3 , 34 , 54 ? 其中哪些将是值: 33454 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. 为什么不在textchanged事件期间将文本框中的当前值保存在变量中。 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 = txtName.Text;

string currentVal can be used as a previous value in text_changed event. string currentVal可以用作text_changed事件中的先前值。

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. 这样您就可以使用旧输入触发void。

private string oldInput;

....

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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