1

In the groupBox control, there are four checkBox element and their tags' names are 1, 2, 3, 4. checkBox1, checkBox3 and checkBox4 are selected. Here is the screenshot:

enter image description here

I want to add selected checkbox items' tag to List item. I tried like this:

private void button1_Click(object sender, EventArgs e)
{
    List<int> filter = new List<int>();

    var add_tags = groupBox1.Controls.OfType<CheckBox>().Where(cb => cb.Checked).ForEach(cbx => filter.Add(Convert.ToInt32(cbx.Tag)));

}

But it returns error and I don't understand the error.

Here is the screenshot:

enter image description here

3
  • 1
    What does the error say? Commented Mar 27, 2018 at 10:13
  • 2
    A bit complicated, but you cannot assign a ForEach, you are storing yet to the filter, you don't need the add_tags var. Commented Mar 27, 2018 at 10:18
  • @Pranay Rana, Yes absolutely. I want to click thick for the first time. But site said that you can not accept in 5 minutes. Later, I forgot. Sorry and thank you very much again. Commented Mar 27, 2018 at 13:34

2 Answers 2

4

If you want all selected checkboxes tags in a list then you can do like this, right now you are not using function other than Select

 List<int> filter = groupBox1.Controls.OfType<CheckBox>()
                      .Where(cb => cb.Checked)
                     .Select(cbx => Convert.ToInt32(cbx.Tag))
                     .ToList();

assuming that all tags are int.


if you want to avoid any error related parsing you can try like this

 List<int> filter = groupBox1.Controls.OfType<CheckBox>()
                             .Where(cb => cb.Checked)
                             .Select(cbx => parseTag(cbx.Tag.toString()))
                             .ToList();

private int parseTag(string tag) 
{   
  int num;   
  if (!Int32.TryParse(tag, out num)) 
  {
    num = int.MaxValue; // or int.MinValue - however it should show up in sort   
  }
  return num; 
}
Sign up to request clarification or add additional context in comments.

4 Comments

Select should start with cap. letter
select -> Select
@Marc - thanks too many typos updated...effect of working with typescript.. thanks again
@MarkBenovsky - thanks too many typos updated...effect of working with typescript.. thanks again
1

Modifying your code a little bit, this must work:

groupBox1.Controls.OfType<CheckBox>().Where(cb => 
cb.Checked).ToList().ForEach(cbx => filter.Add(Convert.ToInt32(cbx.Tag)));

don't assign it to a variable as ForEach (the last called method in the expression chain) doesn't return a value, it just does something (Action) and you already adding to the filter list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.