gpt4 book ai didi

c# - 如何在 TextChanged 中获取新文本?

转载 作者:可可西里 更新时间:2023-11-01 03:01:08 26 4
gpt4 key购买 nike

在 TextBox 中,我正在监视文本更改。我需要在做一些事情之前检查文本。但我暂时只能查看旧文本。我怎样才能得到新的文本?

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

我知道 .NET Framework 4.5 有新的 TextChangedEventArgs 类,但我必须使用 .NET Framework 2.0。

最佳答案

获得新值(value)

您可以只使用 TextBoxText 属性。如果此事件用于多个文本框,那么您将需要使用 sender 参数来获取正确的 TextBox 控件,如下所示...

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

获取旧值

对于那些希望获得旧值的人,您需要自己进行跟踪。我会建议一个简单的变量,它开始时为空,并在每个事件结束时发生变化:

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

如果您打算经常使用它,您可以创建自己的继承自内置控件的 TextBox 控件,并添加此附加功能。

关于c# - 如何在 TextChanged 中获取新文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14337057/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com