Stack overflow looping a checkbox
I have an intermittent error with the code below.
Basically I have a checkbox populated by the database I also manually insert "Select all".
I then use the Selected Item event to either Check or unckeck all the items if they select or unselect the row containing "Select All"
However this method occasionally causes stack overflow
on for (int x = 0; x <= y - 1; x++)
As it seems an intermittent problem is there a way to handle this?
Code:
this.chklstboxReportNames.Items.Add("Select All");
foreach (DataRow dr in corpReportsLibraryDS.DataTable_UP_GetListOfReports.Rows)
{
chklstboxReportNames.Items.Add(dr["ReportName"].ToString());
}
private void chklstboxReportNames_ItemCheck(object sender, ItemCheckEventArgs e)
{
string itemvalue = chklstboxReportNames.Items[e.Index].ToString();
if (itemvalue == "Select All")
{
int y = chklstboxReportNames.Items.Count;
if (e.NewValue == CheckState.Checked)
{
for (int x = 0; x <= y - 1; x++)
{
if (x > 0)
{
chklstboxReportNames.SetItemChecked(x, true);
}
}
}
else
{
for (int x = 0; x <= y - 1; x++)
{
if (x > 0)
{
chklstboxReportNames.SetItemChecked(x, false);
}
}
}
}
}
Re: Stack overflow looping a checkbox
Let me see if I can illustrate the problem:
The "Select All" is an option in your check list box... so when you check it, it starts looping through the items, checking it... which causes the event to fire again... assuming the first item (index 0) is the Select All ... it then starts the loop again... firing the event, again... unchecking the first item (your Select All) causing the even to fire... again... loop... again... set the first item... again.... it's like a M.C. Eicher image... folding in on itself... eventuall the stack fills up with the event calls.
1) move the "select all" to outside the list box
2) set a static flag so that subsequent calls to the event handler don't re-run the loop
3) inside the event handler, remove the error handler from the itemCheck event, add it back after you're done looping.
-tg