-2

Trying to add to list boxes to a List of list boxes in a loop instead of adding each one manually in my code.

Would like to use a for loop and add the item to my list like below.

listOfListBoxes.Add(listBox[i])

instead of...

listOfListBoxes.Add(listBox1);
listOfListBoxes.Add(listBox2);
listOfListBoxes.Add(listBox3);
listOfListBoxes.Add(listBox4);
listOfListBoxes.Add(listBox5);
listOfListBoxes.Add(listBox6);
4
  • Where are these ListBox's defined at or coming from? Have you tried a for if so what is the issue? Commented Jul 18, 2019 at 21:01
  • This is a common scneanrio with WinForms and Web Based scenarios. For Winforms see these two questions and answers . stackoverflow.com/questions/21633826/… stackoverflow.com/questions/9368748/… For Web you can use repeaters or "grid" template scenarios. Commented Jul 18, 2019 at 21:09
  • for (int i = 0; i < Controls.Count; i++) { if (Controls[i] is ListBox) listOfListBoxes.Add(Controls[i] as ListBox); } Commented Jul 18, 2019 at 21:10
  • 1
    @RufusL or somewhat a little shorter (Controls[i] is ListBox lBox)... then just add the lBox to the list... Commented Jul 18, 2019 at 21:13

1 Answer 1

2

I suppose that your listboxes are defined in a Form (this). So you can simply get all the listboxes from the Controls collection with this line and add them with AddRange

listOfListBoxes.AddRange(this.Controls.OfType<ListBox>());

The Controls collection contains all the controls of your form defined at design time and created with the InitializeComponent call. This collection could be used in a loop and checked for every element if it is a ListBox with something like this code

foreach(Control c in this.Controls)
{
    ListBox lb = c as ListBox;
    if(lb != null) 
        listOfListBoxes.Add(lb);    
}

but the introduction of the IEnumerable extensions in the namespace Linq has given the opportunity to avoid the explicit loop above and use the extension OfType that does the loop internally and yields each element of the type requested.
Finally you could add all these elements returned by OfType as an array to List.AddRange method

Sign up to request clarification or add additional context in comments.

2 Comments

Introducing linq may not be something the OP understands (maybe a good time to learn), maybe should have clarified and waited on OP to show what they have done so things can be clarified. Currently it's a good solution of course, but doesn't explain at all if possible what would be wrong with what they have attempted.
Thank you! That was exactly was I was wanting to do.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.