如何使用C#获取已选中的复选框列表框中新选项的文本?

4

我正在使用ItemCheckEventArgs,通过它可以获取一个索引值,但是我不确定如何根据该值查找被选中的项目的文本内容。

4个回答

6

这里是一些基本的代码,可以完成任务:

public void CheckedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
    var checkedListBox = (CheckedListBox)sender;
    var checkedItemText = checkedListBox.Items[e.Index].ToString();
}

5
在ItemCheck事件处理程序中,使用ItemCheckEventArgs e可以检索相应的对象。
checkedListBox1.Items[e.Index]

1

CheckedListBox 类具有 CheckedItems 属性。

private void WhatIsChecked_Click(object sender, System.EventArgs e) {
    // Display in a message box all the items that are checked.

   // First show the index and check state of all selected items.
   foreach(int indexChecked in checkedListBox1.CheckedIndices) {
       // The indexChecked variable contains the index of the item.
       MessageBox.Show("Index#: " + indexChecked.ToString() + ", is checked. Checked state is:" + checkedListBox1.GetItemCheckState(indexChecked).ToString() + ".");
   }

    // Next show the object title and check state for each item selected.
    foreach(object itemChecked in checkedListBox1.CheckedItems) {

        // Use the IndexOf method to get the index of an item.
        MessageBox.Show("Item with title: \"" + itemChecked.ToString() + 
            "\", is checked. Checked state is: " + checkedListBox1.GetItemCheckState(checkedListBox1.Items.IndexOf(itemChecked)).ToString() + ".");
    }

}

这将为他提供所有已选项目。OP明确表示他想要触发事件的项目文本... - Justin Niessner
1
@Justin Niessner:没错。它还展示了如何通过Items索引属性仅获取一个元素:checkedListBox1.Items.IndexOf(itemChecked)).ToString()。这将打印出确切的枚举项,因此OP可以查看不同的集合以使用CheckedListBox对象,并且他可以看到如何获取其中一个。一箭双雕! - Will Marcouiller

0
SelectedIndexChanged 事件中,放置以下代码。
string text = (sender as CheckedListBox).SelectedItem.ToString();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接