0

I am trying to Loop through the tabpages of a tabcontrol in c#. Each tabpage has multiple textboxes. The purpose is to sum up all of the values of these textboxes.

double sum = 0;
foreach(TabPage tbp in tabControl1.TabPages)
{
    foreach(System.Windows.Forms.Control c in tbp.Controls)
    {
            if (c.ToString() == "TextBox")
            {
                sum += Convert.ToDouble(c.Text);
            }
        }
    }

When I execute this code, the first foreach loop is entered three times even though I have one TabPage in my TabControl. Furthermore, the if statement is not entered, so there seems to be something wrong with that as well.

  • 3
    did you try using breakpoints and looking at what its doing? – slow Apr 12 '18 at 06:58
  • 1
    This should work, so USE the DEBUGGER !! - Also it won't get textboxes which are nested deeper, e.g. in panels or groupboxes.. Then you could go for a recursive function. – TaW Apr 12 '18 at 08:18
  • 1
    Whoops, this `if (c.ToString() == "TextBox")` is nonsense. It could be written as `if (c is TextBox)`. But why you loop 3 times over one page must be checked with the debugger!! ((And of course the debugger would have told you what c.ToString actuall looks like..)) – TaW Apr 12 '18 at 10:10

1 Answers1

0

This code (C#7) allows you to safety sum all text boxes values in a tab control, include text boxes nested in children container controls (example: a text box in panel, and the panel in a tab page)

    private double SumTextBoxesValues()
    {
        double sum = 0;
        foreach (TabPage tbp in tabControl1.TabPages)
        {
            var textBoxes = GetAllTextBoxes(tbp);

            foreach (var textBox in textBoxes)
            {
                if(double.TryParse(textBox.Text, out double value))
                    sum += value;
            }

        }

        return sum;
    }

    private static IEnumerable<TextBox> GetAllTextBoxes(Control container)
    {
        var controlList = new List<TextBox>();
        foreach (Control c in container.Controls)
        {
            controlList.AddRange(GetAllTextBoxes(c));

            if(c is TextBox box)
                controlList.Add(box);
        }
        return controlList;
    }
Giancarlo Melis
  • 697
  • 4
  • 17