A Programmer
A Programmer

Reputation: 655

how to check items in checkboxlist?

i have a checkboxlist that i want to check some of it's items, items that i wanna check store in database, i'm selecting them from database and in a loop i wrote thees but just last item selected :(( :

var selectedRoles = (from r in DataContext.Context.Core_PagesPermission 
                     where r.PageName.Contains(pageName) select r)
                        .FirstOrDefault();
if(selectedRoles != null)
{
     string roles = selectedRoles.Roles;
     string[] role = roles.Split(',');
     int countTags = role.Count();
     foreach (string word in role)
     {
        CheckBoxList1.SelectedValue = word;
        Response.Write(word + "<br/>");
        countTags -= 1;
     }
 }

this worked :

var selectedRoles = (from r in DataContext.Context.Core_PagesPermission where r.PageName.Contains(pageName) select r)
                            .FirstOrDefault();
                        dsRoles.DataBind();
                        CheckBoxList1.DataBind();
                        if(selectedRoles != null)
                        {
                        string roles = selectedRoles.Roles;
                        string[] role = roles.Split(',');
                        foreach (string word in role)
                        {
                            try
                            {
                                CheckBoxList1.Items.FindByValue(word).Selected = true;
                            }
                            catch (Exception exp)
                            {
                                lbError.Text= exp.ToString();
                            }

Upvotes: 1

Views: 7208

Answers (2)

Burak Hacıhan
Burak Hacıhan

Reputation: 1

datatable method checkboxlist

for (int i = 0; i < dt.Rows.Count; i++)
{
    chkCategories.Items.FindByValue(dt.Rows[i]["CategoryID"].ToString()).Selected = true;   
}

Upvotes: 0

Slippery Pete
Slippery Pete

Reputation: 526

You will want to select the individual items:

CheckBoxList1.Items.FindByText(word).Selected = true;

or

CheckBoxList1.Items.FindByValue(word).Selected = true;

However, if the checkboxlist doesn't have the text/value you are looking for, it will throw an error.

Upvotes: 2

Related Questions