0

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!

Daniel Lidström
  • 9,930
  • 1
  • 27
  • 35

1 Answers1

4

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;
            }
        }