【问题标题】:How to get the NEW text in TextChanged?如何在 TextChanged 中获取新文本?
【发布时间】:2012-12-29 12:16:39
【问题描述】:

在 TextBox 中,我正在监视文本更改。在做一些事情之前,我需要检查文本。但我现在只能检查旧文本。如何获得新的文本?

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

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

【问题讨论】:

标签: c# events text textbox


【解决方案1】:

看看textbox eventsKeyUp、KeyPress等。例如:

private void textbox_KeyUp(object sender, KeyEventArgs e)
{
    // Do whatever you need.
}

也许这些可以帮助您实现您正在寻找的东西。

【讨论】:

    【解决方案2】:

    即使使用较旧的 .net fw 2.0,如果不在 textbox.text 属性本身中,您仍然应该在 eventArgs 中拥有新旧值,因为事件是在文本更改之后而不是在文本更改期间触发的。

    如果您想在更改文本时执行某些操作,请尝试使用 KeyUp 事件而不是 Changed。

    【讨论】:

      【解决方案3】:

      获得新价值

      您可以只使用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 控件,该控件继承自内置控件,并添加此附加功能。

      【讨论】:

      • 我可以发誓刚才我在这次活动中只看到了旧版本的 Text。现在文本在事件之前被更改。所以现在这个问题是多余的。
      【解决方案4】:
      private void stIDTextBox_TextChanged(object sender, EventArgs e)
      {        
          if (stIDTextBox.TextLength == 6)
          {
              studentId = stIDTextBox.Text; // Here studentId is a variable.
      
              // this process is used to read textbox value automatically.
              // In this case I can read textbox until the char or digit equal to 6.
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多