Kuess Kuess - 1 year ago 118
C# Question

How to ensure ItemCheck occurs before calls inside the event method

So the issue is quite simple really. I have a checkedListBox and on ItemCheck I want to call my Method UpdateGraph(). The problem is, if I call it in the event, it runs through the UpdateGraph method before the item is considered check. Since the update graph method uses a foreach (var item in checkListBox.CheckedItems)
its important that the new value of checked or not is already applied.

I tried a workaround by manually setting the new value in the event however, this gave me a StackOverflowException.

private void checkedListBox3_ItemCheck(object sender, ItemCheckEventArgs e)
{

if (e.NewValue == CheckState.Checked)
{
checkedListBox3.SetItemChecked(e.Index, true);
}
else
{
checkedListBox3.SetItemChecked(e.Index, false);
}

UpdateChart();
}


it gives me the exception on the line where i SetItemChecked.
Just to re-state, I want the item to be checked BEFORE UpdateChart(), and just calling UpdateChart() doesn't seem to do this. Does anyone have any workarounds to make the item checked before it goes into the UpdateChart() method?

EDIT: Thanks, I understand now why I was getting StackOverflowException now, however is there anyway to ensure the item takes on the new CheckState without manually passing it through to my UpdateGraph method? Its a bit of a universal method that wont always be going through my checkedListBox3_itemCheck event so passing in a newCheckstate could complicate things. Mind you I can just use an If to check my passed in value anduse an identifier of some sort to determine whether it needs to be used, but that will probably be my last solution if I cant find anything else to update the checkstate before going into the method.

Answer Source

As the you pointed out there is no OnItemChecked event that happens after the value is set so you'll have to think of another way:

You could refactor your update method to something like UpdateGraph(int? changedIndex = null, bool isChecked = false) That way you can call it just as UpdateGraph() where you currently use it and then

private void checkedListBox3_ItemCheck(object sender, ItemCheckEventArgs e)
{
    UpdateGraph(e.Index, e.NewValue == CheckState.Checked);
}

After evaluating your foreach as normal you can then check for changedIndex == null and react accordingly.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download