在 Windows 窗体 CheckedListBox 控件中呈现数据时,可通过遍历存储在 CheckedItems 属性中的集合或使用 GetItemChecked 方法逐行遍历列表,以确定已选中哪些项。
GetItemChecked 方法采用项索引号作为其参数,并返回 true
或 false
。
SelectedItems 和 SelectedIndices 属性并不像你想的那样,它们不是用来确定已选中哪些项;而是确定已突出显示哪些项。
确定 CheckedListBox 控件中的选中项
遍历 CheckedItems 集合,从 0 开始,因为集合是从零开始的。 请注意,此方法将为你提供选中项列表中的项编号,而不是整个列表。 因此,如果未选中列表中的第一项,而选中了第二项,那么下面的代码将显示像“Checked Item 1 = MyListItem2”这样的文本。
' Determine if there are any items checked. If CheckedListBox1.CheckedItems.Count <> 0 Then ' If so, loop through all checked items and print results. Dim x As Integer Dim s As String = "" For x = 0 To CheckedListBox1.CheckedItems.Count - 1 s = s & "Checked Item " & (x + 1).ToString & " = " & CheckedListBox1.CheckedItems(x).ToString & ControlChars.CrLf Next x MessageBox.Show(s) End If
// Determine if there are any items checked. if(checkedListBox1.CheckedItems.Count != 0) { // If so, loop through all checked items and print results. string s = ""; for(int x = 0; x < checkedListBox1.CheckedItems.Count ; x++) { s = s + "Checked Item " + (x+1).ToString() + " = " + checkedListBox1.CheckedItems[x].ToString() + "\n"; } MessageBox.Show(s); }
// Determine if there are any items checked. if(checkedListBox1->CheckedItems->Count != 0) { // If so, loop through all checked items and print results. String ^ s = ""; for(int x = 0; x < checkedListBox1->CheckedItems->Count; x++) { s = String::Concat(s, "Checked Item ", (x+1).ToString(), " = ", checkedListBox1->CheckedItems[x]->ToString(), "\n"); } MessageBox::Show(s); }
- 或 -
单步执行 Items 集合,从 0 开始,因为集合从零开始,并为每个项调用 GetItemChecked 方法。 请注意,此方法会提供整个列表中的项编号,因此,如果未选中列表中的第一项,并选中第二个项目,它将显示类似于“Item 2 = MyListItem2”的内容。
Dim i As Integer Dim s As String s = "Checked Items:" & ControlChars.CrLf For i = 0 To (CheckedListBox1.Items.Count - 1) If CheckedListBox1.GetItemChecked(i) = True Then s = s & "Item " & (i + 1).ToString & " = " & CheckedListBox1.Items(i).ToString & ControlChars.CrLf End If Next MessageBox.Show(s)
int i; string s; s = "Checked items:\n" ; for (i = 0; i <= (checkedListBox1.Items.Count-1); i++) { if (checkedListBox1.GetItemChecked(i)) { s = s + "Item " + (i+1).ToString() + " = " + checkedListBox1.Items[i].ToString() + "\n"; } } MessageBox.Show (s);
int i; String ^ s; s = "Checked items:\n" ; for (i = 0; i <= (checkedListBox1->Items->Count-1); i++) { if (checkedListBox1->GetItemChecked(i)) { s = String::Concat(s, "Item ", (i+1).ToString(), " = ", checkedListBox1->Item[i]->ToString(), "\n"); } } MessageBox::Show(s);