2010-07-14 205 views
0

我有一個小問題,我很難排除故障。我只想聽聽你們的一些意見。我有這樣也許8文本框,所有使用相同的TextChange事件如下圖所示:TextBox事件小問題 - C#

private void TextChangeUpdate(object sender, EventArgs e) 
    { 
     if (this.Text.Trim() != "") 
     { 
      txtAmountPaid1.Text = (Convert.ToInt32(txtQuantity1.Text) * Convert.ToDecimal(txtUnitPrice1.Text)).ToString(); 
      txtAmountPaid2.Text = (Convert.ToInt32(txtQuantity2.Text) * Convert.ToDecimal(txtUnitPrice2.Text)).ToString(); 
      txtAmountPaid3.Text = (Convert.ToInt32(txtQuantity3.Text) * Convert.ToDecimal(txtUnitPrice3.Text)).ToString(); 
      txtSubtotalProducts.Text = (Convert.ToDecimal(txtAmountPaid1.Text) + Convert.ToDecimal(txtAmountPaid2.Text) + Convert.ToDecimal(txtAmountPaid3.Text)).ToString(); 

      txtSubtotalExpenses.Text = (Convert.ToDecimal(txtWaterBill.Text) + Convert.ToDecimal(txtElectricBill.Text) + Convert.ToDecimal(txtOfficeRent.Text) + Convert.ToDecimal(txtMiscellaneous.Text)).ToString(); 

      txtProductExpenses.Text = txtSubtotalProducts.Text; 
      txtOtherExpenses.Text = txtSubtotalExpenses.Text; 
      txtTotalExpenses.Text = (Convert.ToDecimal(txtProductExpenses.Text) + Convert.ToDecimal(txtOtherExpenses.Text)).ToString(); 
     } 
    } 

現在我的問題出現在該行:

if (this.Text.Trim() != "") 

我需要檢查哪些文本框正在使用此事件( TextChangeUpdate)。這是因爲我需要檢查值是否等於「」。然而,'this'這個關鍵詞似乎並沒有完成這項工作。

有人幫我嗎? :) 謝謝。

回答

0

你應該有:代替

if (((TextBox)sender).Text.Trim()... 

if (this.Text.Trim() 

你可能還應該測試FO文本= NULL。

var tb = sender as TextBox; 
if (tb.Text != null && tb.Text.Trim()... 
0

使用sender as TextBox並抓取文本。

例子:

if ((sender as TextBox).Text.Trim() != "") 
{ 

//code 

} 
0

「這」指的是你在表單,「發件人」,也就是控制觸發事件

2

您可以查看發件人參數去處理程序,因爲它應該是啓動TextChange事件的TextBox被觸發。只需將其轉換爲文本框,然後檢查對象屬性即可。

0

這正是sender對象的用途。這是對事件來源的參考。在你的情況下,你可以檢查發件人對象的屬性,一旦你正確地將它轉換爲TextBox,就可以檢查你喜歡的任何東西。

2

this可能是你的形式。您需要使用sender但首先你需要將其轉換爲TextBox這樣:

(sender as TextBox).Text.Trim != "" 
0

使用發件人

((TextBox)sender).Text.Length != 0 
+0

注:Text.Length = 0是這將在文本上提供更好的性能=「」字符串比較整數比較! – Stephen 2010-07-14 17:30:27

0

是啊,有什麼克林格說

((Textbox)sender).Text.Trim() 

,除非你不應該需要測試null,因爲即使您將其設置爲null,在檢索時也會返回string.empty。

[注意:(發件人爲文本框)是VB.net格式]