mihai11 mihai11 - 1 month ago 22
C# Question

Foreach sum of textboxes c#

I got 2 panels with textboxes and labels.I am trying to make the sum of panel1.texbox1*panel2.textbox1 + panel1.textbox2... and so on.But when I am running the program it actually shows me the product of all the textboxes.

Here I have the code for creating textboxes and labels:

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++;
}
}
}


And here is the code that I tried to use:

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;
}

Answer

You can do it in one line with linq, but you'll of course have to check for valid input in the text boxes first:

  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();
Comments