Mubsher Mughal
Mubsher Mughal

Reputation: 442

C# - how to get list of textboxes with same tag value in windowform?

I have several TextBoxes on form. I have assigned them the same Tag value. Now I want to access and sum up values of these TextBoxes. 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

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186803

If all the TextBoxes are directly on the form and not within containers (Panels, GroupBoxes 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 TextBoxes 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

Related Questions