walkman
walkman

Reputation: 498

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
}

Upvotes: 0

Views: 4604

Answers (7)

YManaf
YManaf

Reputation: 61

Easiest way:

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

Upvotes: 0

Nicholas Aysen
Nicholas Aysen

Reputation: 580

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
                }

Upvotes: 0

walkman
walkman

Reputation: 498

@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);
      ...
}

Upvotes: 0

Kahbazi
Kahbazi

Reputation: 15015

You can use this code :

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

Upvotes: 1

Barry O&#39;Kane
Barry O&#39;Kane

Reputation: 1187

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.

Upvotes: 0

user6522773
user6522773

Reputation:

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

Upvotes: 3

ccStars
ccStars

Reputation: 825

try

foreach (CheckBox user in   checkedListBox1.CheckedItems)
{

}

Upvotes: 0

Related Questions