Search code examples
c#checkedlistbox

select checkedlistbox items checked based on list


I am binding checked list box with a list of roles which I get from the database by executing select all. I have class Person that have property List of roles. I set property by executing a select role by person id on the database. So for example, my Person has 3 Roles and my checked list box have all of the Roles. Now, i want to edit Person and i want roles he have to be checked when load event on edit form is fired.So :

          //checked list box is filled with List and converted to ListBox
          ((ListBox)rolesClbx).DataSource = BLPersons.SelectRoles();
          ((ListBox)rolesClbx).DisplayMember = "Name";

          //clear only selected (selected and checked are not the same)
          rolesClbx.ClearSelected();

          //person gets 3 roles
          person.Roles = BLPersons.SelectRolesByPersonId(person.PersonID);


          for (int i = 0; i < rolesClbx.Items.Count; i++)
          {
             if (person.Roles.Contains(rolesClbx.Items[i]))
                   rolesClbx.SetItemCheckState(i, CheckState.Checked);
          }

But this is not working because Contains use reference when checking. And references are not the same in person.Roles and rolesClb.Items.


Solution

  • First of all I recommended you to mention your framework (winform/wpf/asp.net/ ...). Then each of above framework, You should use id for comparing each roles. I create a sample code based on win-form which is similar to your code, check it and let me know if you have problem still.

    public class RoleItem
    {
        public int Id { get; set; }
        public string Title { get; set; }
    
        public override string ToString()
        {
            return Title.ToString();
        }
    }   
    
    private void Page_Load(object sender, EventArgs e)
    {
        List<RoleItem> _allRoles = new List<RoleItem>()
        {
            new RoleItem() {Id =1,Title="Role1"},
            new RoleItem() {Id =2,Title="Role2"},
            new RoleItem() {Id =3,Title="Role3"},
            new RoleItem() {Id =4,Title="Role4"},
        };
    
        List<RoleItem> _userRoles = new List<RoleItem>()
        {
            new RoleItem() {Id =1,Title="Role1"},
            new RoleItem() {Id =4,Title="Role4"},
        };
    
    
        rolesClbx.DataSource = _allRoles;
    
        for(int i=0;i< _allRoles.Count; i++)
        {
            if(_userRoles.Any(r => r.Id == _allRoles[i].Id))
            {
                rolesClbx.SetItemChecked(i, CheckState.Checked);
            }
        }
    }
    

    Actually, I created two list, the first one is all roles, and the second one is the roles which assigned to user. according the each roleId i check the CheckListBox Item.