2013-01-15 32 views
13

在文本框中,我正在監視文本更改。我需要在做一些事情之前檢查文本。但我現在只能檢查舊文本。我如何獲得新的文本?如何獲取TextChanged中的新文本?

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

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

+0

您使用的web表單還是贏形式? – Stokedout

回答

11

獲得新值

您可以只使用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控件內置的一個,並將此附加功能,如果你打算使用這個很多。

+5

我可以發誓就在這個事件中,我只看到過舊版本的Text。現在,文字在事件發生前已更改。所以這個問題現在是多餘的。 – Bitterblue

+2

如何獲取舊值呢? – Joel

1

看一看在textbox eventsKeyUp,按鍵響應等。例如:

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

也許這些可以幫助你實現你在找什麼。

0

即使與老.NET FW 2.0,你還是應該在如果不能在textbox.text屬性本身,因爲該事件之後,而不是在文本中修改發射EventArgs的新老值。

如果您想要在文本正在更改時執行某些操作,請嘗試KeyUp事件而不是Changed。

-1
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. 
    } 
} 
相關問題