Reputation: 147
I have a CheckedListBox control with 6 checkboxes to choose from. I am trying to detect the following:
User checks the third index and changes the value from unchecked to checked. Internal: Call an event - Grab the checked value of that third index.
That seems to suggest add a SelectedIndexChanged event. That doesn't tell me the user changed the value.
There's another: SelectedValueChanged.
I don't know if that tells me anything at all either, as the function is:
*_SelectedValueChanged(object sender, EventArgs e)
EventArgs is kind of useless to get this required information.
Again, I simply need to get the checked value of the item the user just selected. I'm not interested in gathering all selected items. Just the current one selected. Thanks.
Upvotes: 1
Views: 4823
Reputation: 19641
In order to get the displayed value (content) of the selected item you can use something like the following:
Console.WriteLine(checkedListBox1.Items[checkedListBox1.SelectedIndex].ToString());
Or a shorter version:
Console.WriteLine(checkedListBox1.SelectedItem.ToString());
To determine if the selected item is checked or not, you can use something like the following:
Console.WriteLine(checkedListBox1.CheckedItems.Contains(checkedListBox1.SelectedItem));
This will be checking if the content of the selected item can be found among the checked items. That could lead to a wrong result if your CheckedListBox has duplicates. To avoid this, you might check for the index instead of the value, like this:
Console.WriteLine(checkedListBox1.CheckedIndices.Contains(checkedListBox1.SelectedIndex));
Edit: An even better solution I just found, is to use the GetItemChecked
method. Something like the following would work perfectly:
Console.WriteLine(checkedListBox1.GetItemChecked(checkedListBox1.SelectedIndex));
Hope that helps :)
Upvotes: 2