0

Hi I'm trying to create a list of ListBox's in ASP.NET so that I can then iterate it to test if it has been selected.

    List<string> con = new List<string>();
    List<ListBox> lb = new List<ListBox>();
    foreach (Control c in _pH_Outer_MainCri.Controls)
    {
        if (c is ListBox)
        {
            con.Add(c.ID.ToString());
            lb.Add(c.??);
        }
    }

I'm getting caught up on that last part. Basically then I can

foreach(ListBox a in lb)
    {
        if(a.TestSelection() == true )
        {
            BuildQuery(a);
        }
    }

Thanks in advance for the help ...

1
  • What exactly is the issue? Are you getting an error or is it not behaving as expected? What were you expecting it to do? Commented May 17, 2011 at 0:21

3 Answers 3

2

If you are adding all listboxes then you would want

lb.Add((ListBox)c);
Sign up to request clarification or add additional context in comments.

Comments

1

You can avoid placing the controls in a list by using LINQ, like this:

var listboxen =
    from control in _pH_Outer_MainCri.Controls
    where control is ListBox
    select control as ListBox;

You can then foreach through the list boxes without having to build an intermediate collection.

1 Comment

I love linq its like the swiss army knife of C#. I like this I thnk it is very elegant, however I can't seem t get it to work "Error 2 Could not find an implementation of the query pattern for source type 'System.Web.UI.ControlCollection'. 'Where' not found. Consider explicitly specifying the type of the range variable 'control"
0

When I get overwhelmed, I often find it helpful to take a step back and think about my structures:

List<ListBox> lb - This is a list and each member in the list is of a type ListBox.

In your loop, you want to pull out all of the listboxes, so when you have: if (c is ListBox) { you know that c is already of the type listbox, which is the same type lb is storing. It is simply a matter of adding c to your collection in lb with lb.Add(c);

Separately - do you really need to store these items only to loop through them again and call BuildQuery? Looping through, putting them in a list, and then looping through that collection again may be extra overhead depending on what you are doing.

1 Comment

This is very true, I've spent so much time building the layout of the controls that I think I need to step back a little. I'm in design mode not functionality mode lol ...

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.