简体   繁体   中英

How to retrieve if an item in a CheckedListBox is checked or not? Winforms C#

I have a foreach() statement running through all items inside a CheckedListBox .

How can I know if a item is or not checked?

If useful here's the code:

foreach (object user in checkedListBoxUsersWhoSee.Items)
{
    // Privileged = if the user is checked he has privileges;
    alias = user.ToString().Substring(user.ToString().Length - 3);
    SelectUserID = new SqlCommand(Properties.Resources.SelectUserID + alias, TeamPWSecureBD);
    userIDAuth = (int)SelectUserID.ExecuteScalar();

    InsertAuths.Parameters.AddWithValue("@idPass", idPass);
    InsertAuths.Parameters.AddWithValue("@idUser", userIDAuth);
    InsertAuths.Parameters.AddWithValue("@Privileged", idPass);

    //Code not finished
}
  for (int i = 0; i < checkedListBoxUsersWhoSee.Items.Count; i++)
  {
    CheckState checkState = checkedListBoxUsersWhoSee.GetItemCheckState(i);
    //CheckState.Checked
    //CheckState.Indeterminate
    //CheckState.Unchecked
  }

You can use this code :

foreach (object user in checkedListBox.Items)
{
    bool Privileged = checkedListBox.GetItemCheckState(checkedListBox.Items.IndexOf(user)) == CheckState.Checked;
}

try

foreach (CheckBox user in   checkedListBox1.CheckedItems)
{

}

CheckedListBox has a property CheckedItems which is a collection of the checked or indeterminate items.

var items = checkedListBoxUsersWhoSee.CheckedItems;

UPDATE I tested adding items to a CheckedListBox and they did not appear under the CheckedItems property suggesting that by default they are initialized with the value Unchecked .

@Arvin had given the right answer but idkw he edited to a more confuse way of solving the problem.

The code below is working like a charm so please to the person who edited the correct answer stop messing around.

foreach (object user in checkedListBoxUsersWhoSee.Items)
{
      Privileged = checkedListBoxUsersWhoSee.CheckedItems.Contains(user);
      ...
}

I used the following:

                ArrayList selected = new ArrayList();
                for (int i = 0; i < chkRoles.Items.Count; i++) //chkRoles being the CheckBoxList
                {
                    if (chkRoles.GetItemChecked(i))
                        selected.Add(chkRoles.Items[i].ToString()); //And I just added what was checked to the Arraylist. String values
                }

Easiest way:

foreach(ListItem item in checkedListBoxUsersWhoSee.Items){    
   if (item.Selected){
       // LOGIC HERE
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM