开发者

How would I get the text of the newly checked item in a checked listbox with C#

I'm using the ItemCheckEventArgs and from which I can get an index value, but from this value I'm not sure how to look up what the text is of whatever wa开发者_运维问答s checked.


Here's some bare-bones code that should do the trick:

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


In ItemCheck event handler using ItemCheckEventArgs e you can retrive corresponding object

checkedListBox1.Items[e.Index]


The CheckedListBox class has a CheckedItems property.

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() + ".");
    }

}


Inside the SelectedIndexChanged event, put the following code

string text = (sender as CheckedListBox).SelectedItem.ToString();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜