Reputation: 217
I have a CheckedListBox in a form. Each item represents an email message subject of a logged in user.
What I try to achieve is that when only one item is selected, both the Edit and Delete buttons should be enabled, otherwise disabled.
I have tried to use the following event handler after setting the CheckOnClick property to true, but it's not working:
private void clbEmailsSubjects_Click(object sender, EventArgs e)
{
btnEdit.Enabled = btnDelete.Enabled = (clbEmailsSubjects.CheckedItems.Count == 1);
}
Any suggestions?
Edit: I had selected an item, but both buttons were still disabled.
Now, after selecting the second item they have become enabled:
The effect seems to be contrary. I think the value of CheckedItems.Count might be updated after the event_handler is executed.
Upvotes: 0
Views: 1009
Reputation: 8551
It would be more correct to use the ItemCheck
event than the Click
event (as the click may not have landed on a checkbox). But either way, the event gets fired before the Checked
property on the CheckBox
gets changed, so you can't set the enabled states within either of those event handlers. You can, however, defer the handling until events are processed using BeginInvoke
, like this:
private void clbEmailsSubjects_ItemCheck(object sender, ItemCheckEventArgs e)
{
BeginInvoke((Action)(() =>
{
btnEdit.Enabled = btnDelete.Enabled =
(clbEmailsSubjects.CheckedItems.Count == 1);
}));
}
Upvotes: 2
Reputation: 2233
You need to register for the ItemCheck
event on your CheckedListBox
. Then the following code will give you the desired result:
private void clbEmailsSubjects_ItemCheck(object sender, ItemCheckEventArgs e)
{
btnEdit.Enabled = btnDelete.Enabled =
(clbEmailsSubjects.CheckedItems.Count == 2 && e.NewValue == CheckState.Unchecked) ||
(clbEmailsSubjects.CheckedItems.Count == 0 && e.NewValue == CheckState.Checked);
}
Upvotes: 1