Getting CheckBoxList Item values

前端 未结 8 822
野的像风
野的像风 2021-01-04 10:53

I have a CheckBoxList which I\'m populating with data. When I attempt to retrieve the checked items from the list I can only grab the item ordinal, I cannot get the value.

8条回答
  •  误落风尘
    2021-01-04 11:14

    to get the items checked you can use CheckedItems or GetItemsChecked. I tried below code in .NET 4.5

    Iterate through the CheckedItems collection. This will give you the item number in the list of checked items, not the overall list. So if the first item in the list is not checked and the second item is checked, the code below will display text like Checked Item 1 = MyListItem2.

    //Determine if there are any items checked. 
    if(chBoxListTables.CheckedItems.Count != 0)  
    {
        //looped through all checked items and show results.
        string s = "";
        for (int x = 0; x < chBoxListTables.CheckedItems.Count; x++)
        {
            s = s + (x + 1).ToString() + " = " + chBoxListTables.CheckedItems[x].ToString()+ ", ";
        }
        MessageBox.Show(s);//show result
    }
    

    -OR-

    Step through the Items collection and call the GetItemChecked method for each item. This will give you the item number in the overall list, so if the first item in the list is not checked and the second item is checked, it will display something like Item 2 = MyListItem2.

    int i;  
    string s;   
    s = "Checked items:\n" ;  
    for (i = 0; i < checkedListBox1.Items.Count; i++)  
    {  
       if (checkedListBox1.GetItemChecked(i))  
       {  
          s = s + "Item " + (i+1).ToString() + " = " + checkedListBox1.Items[i].ToString() + "\n";  
       }  
    }  
    MessageBox.Show (s);
    

    Hope this helps...

提交回复
热议问题