C# 如何遍历复选框列表并查找已选中和未选中的内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/395454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to loop through a checkboxlist and to find what's checked and not checked?
提问by Bill Martin
I'm trying to loop through items of a checkbox list. If it's checked, I want to set a value. If not, I want to set another value. I was using the below, but it only gives me checked items:
我正在尝试遍历复选框列表的项目。如果选中,我想设置一个值。如果没有,我想设置另一个值。我使用的是下面的,但它只给了我检查的项目:
foreach (DataRowView myRow in clbIncludes.CheckedItems)
{
MarkVehicle(myRow);
}
采纳答案by Robert C. Barth
for (int i = 0; i < clbIncludes.Items.Count; i++)
if (clbIncludes.GetItemChecked(i))
// Do selected stuff
else
// Do unselected stuff
If the the check is in indeterminate state, this will still return true. You may want to replace
如果检查处于不确定状态,这仍将返回 true。你可能想更换
if (clbIncludes.GetItemChecked(i))
with
和
if (clbIncludes.GetItemCheckState(i) == CheckState.Checked)
if you want to only include actually checked items.
如果您只想包含实际检查的项目。
回答by devio
Use the CheckBoxList's GetItemChecked or GetItemCheckState method to find out whether an item is checked or not by its index.
使用 CheckBoxList 的 GetItemChecked 或 GetItemCheckState 方法来确定项目是否通过其索引被选中。
回答by JasonS
Try something like this:
尝试这样的事情:
foreach (ListItem listItem in clbIncludes.Items)
{
if (listItem.Selected) {
//do some work
}
else {
//do something else
}
}
回答by Contra
This will give a list of selected
这将给出一个选定的列表
List<ListItem> items = checkboxlist.Items.Cast<ListItem>().Where(n => n.Selected).ToList();
This will give a list of the selected boxes' values (change Value for Text if that is wanted):
这将给出所选框值的列表(如果需要,更改文本的值):
var values = checkboxlist.Items.Cast<ListItem>().Where(n => n.Selected).Select(n => n.Value ).ToList()
回答by sameer sharma
check it useing loop for each index in comboxlist.Items[i]
检查它使用循环中的每个索引 comboxlist.Items[i]
bool CheckedOrUnchecked= comboxlist.CheckedItems.Contains(comboxlist.Items[0]);
I think it solve your purpose
我认为它解决了你的目的
回答by iviorel
I think the best way to do this is to use CheckedItems
:
我认为最好的方法是使用CheckedItems
:
foreach (DataRowView objDataRowView in CheckBoxList.CheckedItems)
{
// use objDataRowView as you wish
}