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.
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.