views:

6192

answers:

4

Hi, i'm trying to loop thru items of a checkbox list. if it's checked, I want to set 1 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);
}

TIA!

A: 

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

devio
+3  A: 

Try something like this:

foreach (ListItem listItem in clbIncludes.Items)
{
    if listItem.Selected { //do some work }
    else { //do something else }
}
JasonS
It's winform. So, when i try to reference listitem, it's wanting to reference a the web control. i tried using a listviewitem and get the error 'Unable to cast object of type 'System.Data.DataRowView' to type 'System.Windows.Forms.ListViewItem'. Thoughts
asp316
+1  A: 
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.

Robert C. Barth
Using this worked great. How can I get the value/value member of the checked checkbox?
asp316
A: 

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()
Contra