Reputation: 442
I have several TextBox
es on form. I have assigned them the same Tag
value. Now I want to access and sum up values of these TextBox
es. I have tried the following but it didn't work. Even it didn't throw any exception. But the control exit from the function before foreach loop. Any help will be appreciated. Thanks in advance.
private void CalculateExpense()
{
int sum = 0;
var textBoxes = this.Controls
.OfType<TextBox>()
.Where(d => d.Tag.ToString() == "ExpenseField")
.ToList();
foreach (var item in textBoxes)
{
sum = sum + Convert.ToInt16(!string.IsNullOrEmpty(item.Text) ? item.Text : "0");
}
this.TotalExpenseLbl.Text = sum.ToString();
this.TotalMonthlyExpenses.Text = sum.ToString();
}
Upvotes: 0
Views: 519
Reputation: 186803
If all the TextBox
es are directly on the form and not within containers (Panel
s, GroupBox
es etc).
int sum = Controls
.OfType<TextBox>()
.Where(box => string.Equals("ExpenseField", box.Tag as String))
.Select(box => int.TryParse(box.Text, out var v) ? v : 0)
.Sum();
this.TotalExpenseLbl.Text = sum.ToString();
this.TotalMonthlyExpenses.Text = sum.ToString();
It seems, that the main problem in your code is in d.Tag.ToString()
since Tag
is null
by default.
Edit: in case TextBox
es are within several containes, you have to use recursion instead of Controls
collection:
private static IEnumerable<Control> GetAll(Control control) {
var controls = control.Controls.OfType<Control>();
return controls
.SelectMany(ctrl => GetAll(ctrl))
.Concat(controls);
}
...
int sum = GetAll(this)
.OfType<TextBox>()
.Where(box => string.Equals("ExpenseField", box.Tag as String))
.Select(box => int.TryParse(box.Text, out var v) ? v : 0)
.Sum();
this.TotalExpenseLbl.Text = sum.ToString();
this.TotalMonthlyExpenses.Text = sum.ToString();
Upvotes: 3