C# Destroying the effects of a class -
i have public class puzzle creates puzzle of buttons (a 2d array of buttons) , places them in form1 of windows form application(it sets form1 parent). when call function remove these buttons except reset_button, delete half of them. have call method n times in order these buttons deleted, n x n = number of buttons puzzle has.
public void remove(form g) { (int i=0; i<n;i++) foreach (button b in g.controls) { if (b.name!="btn_reset") b.dispose(); } }
in form1 class puzzle new instance of class puzzle, , remove public method within class puzzle
btn_reset.mouseclick += (ss, ee) => { puzzle.remove(this); //puzzle=new puzzle(n,this); };
any idea why happens?
you not removing buttons disposing them. suggest code:
public void remove(form g) { var toremove = g.controls.oftype<button>().where(x => x.name != "btn_reset").tolist(); foreach(button b in toremove) { g.controls.remove(b); } }
please note:
- you have create new list of controls (
toremove
in example) because cannot directly iterate oncontrols
, remove items list. - you have add
using system.linq;
update: stated other users, dispose removes controls parent. actual problem not call dispose
way used iterator .so use code
public void remove(form g) { var toremove = g.controls.oftype<button>().where(x => x.name != "btn_reset").tolist(); foreach(button b in toremove) { b.dispose(); } }
Comments
Post a Comment