c# - Close a form on CheckChanged event -


i have section of code, opens form when box checked, closes when box unchecked:

private void chkdupe_checkedchanged(object sender, eventargs e) {       if (chkdupe.checked == true)     {         input = 1;         cableid_controller.showduplicateview(main_menu, this);     }     else if (chkdupe.checked == false)     {         // close form.         formcollection fc = application.openforms;         foreach (form frm in fc)         {             if (frm cableid_duplicateview)             {                 frm.close();             }         }     } } 

it opens form fine, when uncheck box, error:

invalidoperationexception. collection modified; enumeration may not execute.

i know has foreach loop, can't think of way substitute else. can provide suggestions?

you modifying application.openforms collection while iterating it. need create copy before iterate on copy instead of original collection

var fc = application.openforms.oftype<form>().tolist(); 

also, if want close cableid_duplicateview forms, can use :

var fc = application.openforms.oftype<cableid_duplicateview>().tolist();  foreach (form frm in fc)       frm.close(); 

and remove type check loop.


Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -