[英]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
.我有一个
foreach()
语句贯穿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. CheckedListBox
有一个属性CheckedItems
,它是已检查或不确定项目的集合。
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
.更新我测试了将项目添加到
CheckedListBox
并且它们没有出现在CheckedItems
属性下,这表明默认情况下它们是用值Unchecked
初始化的。
@Arvin had given the right answer but idkw he edited to a more confuse way of solving the problem. @Arvin 给出了正确的答案,但 idkw 他编辑了一种更令人困惑的解决问题的方法。
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.