0

I'm trying to select values in a CheckBoxList control based on a data source. I have five items in the CheckBoxList and three items in the data source, but in the loop I only get one item selected.

if (ddlUserId.SelectedIndex != 0)
{
   RoleDetails rd;
   rd = CatalogAccess.GetSingleUserRole(ddlUserId.SelectedValue.ToString());

   for (int i = 0; i < cblRoles.Items.Count; i++)
   {
      cblRoles.Items.FindByValue(rd.RoleID.ToString()).Selected = true;
   }
}

I tried this, but it still selects only one item:

RoleDetails rd;

for (int i = 0; i < cblRoles.Items.Count; i++)
{            
   rd = CatalogAccess.GetSingleUserRole(ddlUserId.SelectedValue.ToString());

   if (cblRoles.Items[i].Value == rd.RoleID.ToString())
      cblRoles.Items[i].Selected = true;
}

CheckboxList bind code

  cblRoles.DataSource = CatalogAccess.GetRoles();
  cblRoles.DataTextField = "RoleDetails";
  cblRoles.DataValueField = "RoleId";
  cblRoles.DataBind();
3
  • please share checkboxlist bind code Commented Jul 26, 2014 at 9:00
  • I have posted the bind code. Commented Jul 26, 2014 at 12:53
  • Does your CheckBoxList have multiple Checkboxes with the same value? You only ever get one RoleDetails object, therefore only one RoleID. So unless the answer to my question is yes, then you will only ever get one selected CheckBox. Commented Jul 27, 2014 at 0:03

1 Answer 1

1

When you use for loop you need to use index value (Here it is "i"), like

 for (int i = 0; i < cblRoles.Items.Count; i++)
 {
   if(cblRoles.Items[i].Value == rd.RoleID.ToString())
           cblRoles.Items[i].Selected = true;
 }

Or you can use foreach as below:

Here i have created looping through items of checkbox list using foreach & item will be made selected id its value will match RoleId .

 foreach (ListItem li in cblRoles.Items)
    {
        if (rd.RoleID.ToString() ==  li.Value)
        {
            li.Selected = true;
        }
        else
        {
            li.Selected = false;
        }
    }
Sign up to request clarification or add additional context in comments.

5 Comments

A little explanation for what you are suggesting in the answer and why the code in OP is not getting the desired results would be helpful.
Still getting only one item selected. I have posted the code.
@ayha for selected user are there more than one role?
There are three roles for the selected user but it select the first role (roleId 1 in the table). I deleted the first item in the table and tried then it doesn't select anything else.
RoleDetails rd; rd = CatalogAccess.GetSingleUserRole(ddlUserId.SelectedValue.ToString()); I think in this way you are fetching one role only. Please make sure you are fetching all assigned roles.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.