0

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>

3
Contributors
3
Replies
6
Views
7 Years
Discussion Span
Last Post by jbisono
1

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.

Edited by jbisono: n/a

0

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;
    }
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.