views:

43

answers:

1

Hello,

I have a situation where I need to databind a string array to a CheckBoxList. The decision if each item should be checked, or not, needs to be done by using a different string array. Here's a code sample:

string[] supportedTransports = ... ;// "sms,tcp,http,direct"
string[] transports = ... ; // subset of the above, i.e. "sms,http"
// bind supportedTransports to the CheckBoxList
TransportsCheckBoxList.DataSource = supportedTransports;
TransportsCheckBoxList.DataBind();

This binds nicely, but each item is unchecked. I need to query transports, somehow, to determine the checked status. I am wondering if there is an easy way to do this with CheckBoxList or if I have to create some kind of adapter and bind to that?

Thanks in advance!

+1  A: 

You can use some LINQ for that:

        string[] supportedTransports = { "sms", "tcp", "http", "direct" };
        string[] transports = { "sms", "http" }; 

        CheckBoxList1.DataSource = supportedTransports;
        CheckBoxList1.DataBind();

        foreach (ListItem item in CheckBoxList1.Items)
        {
            if (transports.Contains(item.Text))
            {
                item.Selected = true;
            }
        }
Dave
How do you suppose this is using LINQ? Anyway, if possible, I'd rather set up the databinding and not have to do any post-processing with the items.
Daniel Lidström
I found the answer to a similar question here: http://stackoverflow.com/questions/879434/asp-net-checkboxlist-databinding-question. It confirms your answer Dave.
Daniel Lidström
Aha, now I see where Linq is being used :-) Thanks Dave.
Daniel Lidström