hi,
I want to bind the datasource to a CheckBoxList Based on Database Value i want to check few checkboxes,
ex:
in roles table ModuleIds column contain few ids with ',' seperator
but my checkboxlist contain all modules, now i want to checked which module is in miduleIds field.

<asp:CheckBoxList ID="chklistmodules" runat="server" DataTextField="M_NAME" DataValueField="M_ID">
</asp:CheckBoxList>

cblTest = CheckBoxList control

List<string> AllModules = new List<string>() 
        { 
            "Module1", "Module2", "Module3", "Module4", "Module5", "Module6"
        };
        cblTest.DataSource = AllModules;
        cblTest.DataBind();
        string ModuleIds = "Module2,Module5";
        string[] arrayModule = ModuleIds.Split(',');
        foreach (string st in arrayModule)
        {
            cblTest.Items.FindByText(st).Selected = true;
        }

the above example works great, if you know that every single module in arrayModule exist in the checkboxlist item collection.

To add to what jbisono posted, I would recommend adding a check for null to the FindByText method to account for the possibility that a previously selected item is no longer in the list of available items.

So it would be something like

ListItem listItem = cblTest.Items.FindByText(st);
if (listItem != null)
    listItem.Selected = true;

As an alternative to that method, I would like to present another only because it uses LINQ and I happen to think LINQ is fun. Because I'm a nerd. In this example, I've called the checkboxlist "chkItems."

protected void Page_Load(object sender, EventArgs e)
    {
        List<string> availableItems = new List<string> { "Item1", "Item2", "Item3", "Item4", "Item5" };
        List<string> selectedItems = new List<string> { "Item1", "Item3", "Item4", "Item6" };

        // add available items to checkboxlist control
        foreach (string item in availableItems)
            chkItems.Items.Add(new ListItem(item));

        // check pre-selected items
        var query = from ListItem listItem in chkItems.Items
                    join item in selectedItems
                    on listItem.Value equals item
                    select listItem;

        foreach (ListItem listItem in query)
            listItem.Selected = true;
    }

hey apegram i like your last approach, linq is the best :).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.