2014-02-17 48 views
1

我想提出一個方案來學習如何生成動態內對Button_Click事件循環控制,現在我試圖計算第三文本框兩個領域的乘法和它們的輸出計算在Windows窗體應用程序動態生成的控制

代碼:

for (int i = 0; i < ds.Tables[0].Rows.Count; i++) 
{ 


    unit.Location = new System.Drawing.Point(unitstartposition, unitstartpositionV); 
    unit.Size = new System.Drawing.Size(100, 30); 
    unit.Text = ""; 
    unit.Name = "unit" + i.ToString(); 

    rate.Location = new System.Drawing.Point(ratestartposition, ratestartpositionV); 
    unit.Size = new System.Drawing.Size(100, 30); 
    rate.Text = ""; 
    rate.Name = "rate" + i.ToString(); 

    amt.Location = new System.Drawing.Point(amtstartposition, amtstartpositionV); 
    amt.Size = new System.Drawing.Size(100, 30); 
    amt.Text = ""; 
    amt.Name = "amt" + i.ToString(); 

    panel1.Controls.Add(unit); 
    panel1.Controls.Add(rate); 
    panel1.Controls.Add(amt); 


    unitstartpositionV += 30; 
    ratestartpositionV += 30; 
    amtstartpositionV += 30; 

    unit = new TextBox(); 
    rate = new TextBox(); 
    amt = new TextBox(); 


} 

現在我要計算它像

amt0.Text = (ConvertToInt32(unit0.Text) * ConvertToInt32(rate0.Text)).ToString(); 
amt1.Text = (ConvertToInt32(unit1.Text) * ConvertToInt32(rate1.Text)).ToString(); 

最後我想總結一下所有的(i)。請幫助實現這一點。

回答

0

從行'unitstartpositionV + = 30;'開始以後,這裏是我想出解決這個:

  unitstartpositionV += 30; 
      ratestartpositionV += 30; 
      amtstartpositionV += 30; 

      unit = new TextBox(); 
      rate = new TextBox(); 
      amt = new TextBox(); 
      unit.Tag = rate; 
      rate.Tag = amt; 
      amt.Tag = unit; 


      rate.TextChanged += rate_TextChanged; 
      unit.TextChanged += unit_TextChanged; 
     } 
    } 

    private void rate_TextChanged(object sender, EventArgs e) 
    { 

     var rate = sender as TextBox; 
     var amt = rate.Tag as TextBox; 
     var unit = amt.Tag as TextBox; 
     Calc(rate.Text, unit.Text, amt); 
    } 

    private void unit_TextChanged(object sender, EventArgs e) 
    { 
     var unit = sender as TextBox; 
     var rate = unit.Tag as TextBox; 
     var amt = rate.Tag as TextBox; 
     Calc(rate.Text, unit.Text, amt); 
    } 

    private void Calc(string rate, string unit, TextBox amt) 
    { 
     int rateInt; 

     if (!int.TryParse(rate, out rateInt)) return; 

     int unitInt; 
     if (!int.TryParse(unit, out unitInt)) return; 

     amt.Text = (rateInt * unitInt).ToString(); 
    } 

(不包括所有的總和),我在一個不尋常的方式在這裏解決了這個問題

,以適應與你展示的風格一致。但是你真的應該使用數組,列表或某種'集合'來保存你的控件。從回顧你的其他答案,我不認爲你已經瞭解了IEnumerable。這就是你錯過的概念,會使這種活動變得更加簡單(特別是'所有'總和'的要求)。

相關問題