查找每个文本框的总和

本文关键字:文本 查找 | 更新日期: 2023-09-27 18:14:45

我有2个面板的文本框和标签。我试图使panel1.texbox1*panel2的总和。Textbox1 + panel1.textbox2…等等......但是当我运行程序时,它实际上显示了所有文本框的乘积。

下面是创建文本框和标签的代码:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    int j,c=1;
    int i = comboBox1.SelectedIndex;
    if (i != null)
    {
        for (j = 0; j <= i; j++)
        {
            Label label = new Label();
            label.Text = "w" + c;
            label.Location = new System.Drawing.Point(5, 20 + (20 * c));
            label.Size = new System.Drawing.Size(30, 20);
            panel1.Controls.Add(label);
            Label label2 = new Label();
            label2.Text = "x" + c;
            label2.Location = new System.Drawing.Point(5, 20 + (20 * c));
            label2.Size = new System.Drawing.Size(30, 20);
            panel3.Controls.Add(label2);
            TextBox w = new TextBox();
            w.Text = "";
            w.Location = new System.Drawing.Point(35, 20 + (20 * c));
            w.Size = new System.Drawing.Size(25, 20);
            panel1.Controls.Add(w);
            TextBox x = new TextBox();
            x.Text = "";
            x.Location = new System.Drawing.Point(35, 20 + (20 * c));
            x.Size = new System.Drawing.Size(25, 20);
            panel3.Controls.Add(x);
            c++;
        }
    }
}

下面是我尝试使用的代码:

private void button4_Click(object sender, EventArgs e)
{
    int suma = 0;
    foreach (Control w1 in panel1.Controls.OfType<TextBox>())
    {                            
        foreach (Control w2 in panel3.Controls.OfType<TextBox>())
        {
            int textB1 = int.Parse(w1.Text);
            int textB2 = int.Parse(w2.Text);
            int textB3 = textB1 * textB2;
        }       
    }
    textBox3.Text = "" + suma;  
}

查找每个文本框的总和

您可以在一行中使用linq来完成,但是您当然必须首先检查文本框中的有效输入:

  var panel1Texts = panel1.Controls.OfType<TextBox>().ToArray();
  var panel2Texts = panel2.Controls.OfType<TextBox>().ToArray();
  Func<TextBox, bool> isInvalid = (text) =>
  {
    int res;
    return !int.TryParse(text.Text, out res);
  };
  var errorText = panel1Texts.FirstOrDefault(isInvalid);
  if (errorText != null)
  {
    // Error handling
  }
  errorText = panel2Texts.FirstOrDefault(isInvalid);
  if (errorText != null)
  {
    // Error handling
  }
  var sum = panel1Texts.Zip(panel2Texts, (tb1, tb2) => int.Parse(tb1.Text) * int.Parse(tb2.Text)).Sum();
textBox3.Text = sum.ToString();

在您当前的代码中,您正在通过对它们进行OfType<TextBox>()作为集合也包括标签来将所有控件包括标签转换为文本框。
以下是我认为你应该做的:

 TextBox3.Text = (Panel1.Controls.OfType<Control>().Where(c => c.GetType() == typeof(TextBox)).Sum(v => int.Parse(v.Text)) + Panel2.Controls.OfType<Control>().Where(x => x.GetType() == typeof(TextBox)).Sum(z => int.Parse(z.Text))).ToString();