How to loop through a checkboxlist and to find what's checked and not checked?

后端 未结 6 2151
-上瘾入骨i
-上瘾入骨i 2020-12-18 18:47

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

相关标签:
6条回答
  • 2020-12-18 19:17

    I think the best way to do this is to use CheckedItems:

     foreach (DataRowView objDataRowView in CheckBoxList.CheckedItems)
     {
         // use objDataRowView as you wish                
     }
    
    0 讨论(0)
  • 2020-12-18 19:20
    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

    if (clbIncludes.GetItemChecked(i))
    

    with

    if (clbIncludes.GetItemCheckState(i) == CheckState.Checked)
    

    if you want to only include actually checked items.

    0 讨论(0)
  • 2020-12-18 19:28

    Try something like this:

    foreach (ListItem listItem in clbIncludes.Items)
    {
        if (listItem.Selected) { 
            //do some work 
        }
        else { 
            //do something else 
        }
    }
    
    0 讨论(0)
  • 2020-12-18 19:30

    check it useing loop for each index in comboxlist.Items[i]

    bool CheckedOrUnchecked= comboxlist.CheckedItems.Contains(comboxlist.Items[0]);
    

    I think it solve your purpose

    0 讨论(0)
  • 2020-12-18 19:31

    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()
    
    0 讨论(0)
  • 2020-12-18 19:32

    Use the CheckBoxList's GetItemChecked or GetItemCheckState method to find out whether an item is checked or not by its index.

    0 讨论(0)
提交回复
热议问题