2016-12-05 103 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