2016-12-05 101 views
0

我在GroupBox內有12個文本框和12個標籤。GroupBox內的TextBox事件處理程序

當價格輸入到任何文本框中時,我想要計算稅額並顯示在此文本框旁邊的標籤中。

我已經編寫了計算稅款的代碼,但僅在第一個標籤labelTax01中可見。

我的代碼清單如下:

public void Form1_Load(object sender, EventArgs e)   
{ 
    foreach (Control ctrl in groupBoxPrice.Controls)    
    { 
     if (ctrl is TextBox) 
     { 
      TextBox price= (TextBox)ctrl; 
      price.TextChanged += new EventHandler(groupBoxPrice_TextChanged); 
     } 
    } 
}  

void groupBoxPrice_TextChanged(object sender, EventArgs e)  
{ 
    double output = 0; 
    TextBox price= (TextBox)sender; 

    if (!double.TryParse(price.Text, out output)) 
    { 
     MessageBox.Show("Some Error"); 
     return; 
    } 
    else 
    { 
     Tax tax = new Tax(price.Text);    // tax object 
     tax.countTax(price.Text);     // count tax 
     labelTax01.Text = (tax.Tax);    // ***help*** /// 
    } 
} 
+1

因此每個文本框旁邊都有一個標籤,對吧? – Badiparmagi

回答

3

名稱您的標籤(例如LabelForPrice001,LabelForPrice002,等...),然後在德興時間每個價格文本框的標籤屬性插入此名。

此時發現文本框手段也發現,在該組框控件集合一個簡單的搜索相關標籤....

順便問一下,你會發現非常有用的,可以簡化您的循環,分機OfType

public void Form1_Load(object sender, EventArgs e) 
{ 
    foreach (TextBox price in groupBoxPrice.Controls.OfType<TextBox>())    
    { 
     price.TextChanged += new EventHandler(groupBoxPrice_TextChanged); 
    } 
} 

void groupBoxPrice_TextChanged(object sender, EventArgs e)  
{ 
    double output = 0; 
    TextBox price= (TextBox)sender; 

    if(!double.TryParse(price.Text, out output)) 
    { 
     MessageBox.Show("Some Error"); 
     return; 
    } 
    else 
    { 
     Tax tax = new Tax(price.Text);    
     tax.countTax(price.Text);     

     // retrieve the name of the associated label... 
     string labelName = price.Tag.ToString() 

     // Search the Controls collection for a control of type Label 
     // whose name matches the Tag property set at design time on 
     // each textbox for the price input 
     Label l = groupBoxPrice.Controls 
           .OfType<Label>() 
           .FirstOrDefault(x => x.Name == labelName); 
     if(l != null) 
      l.Text = (tax.Tax);     
    } 
} 
+0

,我準備發佈的內容。做得好! – Badiparmagi