2016-12-05 19 views
0

GroupBox内に12個のテキストボックスと12個のラベルがあります。GroupBox内のTextBoxイベントハンドラ

価格がテキストボックスに入力されると、税額が計算され、このテキストボックスの横に表示されます。

私は税金を計算するコードを書いていますが、最初のラベルにしか表示されません。

次のように私のコードのリストは次のとおりです。

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、等...)、そして最新デザイン時に各価格テキストボックスのTagプロパティにこの名前を挿入します。テキストボックスを見つけるこの時点で

も....グループボックスのControlsコレクション内の単純な検索でところで

を関連付けられたラベルを見つけることを意味、あなたはあなたのループを簡素化するために、非常に便利になります、内線番号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

関連する問題