ItemCheck event of Windows.Forms.CheckedListBox is a BEFORE event, not AFTER
Today I learnt a few things about the Windows.Forms.CheckedListBox, it happened that I was trying to get a comma separated string of the text of all the items that are checked in the CheckedListBox control.
e.g. "Apple, Orange, Mango"
Now this is not so much a problem as we have the CheckedListBox.CheckedItems collection which gives us the items and we can iterate over it and concatenate the values.
// here the objects in the ListBox are strings, chkList is the name of
//CheckedListBox
String resultString = String.Empty;
foreach (string item in chkList.CheckedItems) {
resultString += item + “, “;
}
..
I had used that before and didn’t have any problems, but I wanted result to display as and when the items were being checked/unchecked, the comma separated string would be formed as and when the items were being checked/unchecked. So I looked around for the event that is fired when an item is checked/unchecked in the CheckedListBox control. There is the event ItemCheck which also provides an ItemCheckEventArgs value. Now, this is where I was getting stuck time and again. I was of the opinion that this event is fired AFTER the check/uncheck like all events, so that if we inspect the CheckedItems inside the event handler, we should get the proper result, but then as I found out, this is a BEFORE event meaning that the event handler is fired before the check happens!! Now this can totally throw off the logic and thinking, so here is what I had to do to get the desired effect :-
void LstItemCheck(object sender, ItemCheckEventArgs e)
{
string items = "";
foreach (int i in lst.CheckedIndices) {
// this is the pre-event, i.e. before item is actually checked
// so among the existing CheckedItems it includes the current item being unchecked
// we need to skip that
if (i != e.Index) {
// other checked items
items += lst.Items[i].ToString() + ", ";
}
}
// the existing item will not be in the CheckedItems so we need to include it
if (e.CurrentValue == CheckState.Unchecked) {
items += lst.Items[e.Index].ToString() + ", ";
}
// remove the trailing ‘, ‘
if (items.Length > 0) {
items = items.Remove(items.Length - 2, 2);
label2.Text = items;
} else {
label2.Text = String.Empty;
}
}
Basically, this is what I have understood, a few things need to be kept in mind while working with ItemCheck event :-
1) This is a Before event, in that the action of Check/UnCheck hasn't taken place, so the items in the CheckedItems needs to handled carefully
2) ItemCheckEventArgs.CurrentValue will return and enum of type CheckState but again this state is as of 'now' meaning that the check/uncheck hasn't happened yet. So if we were checking an item, this would show CheckState.Unchecked and if the item is being unchecked, CurrentValue will return CheckState.Checked !!