winforms - Remove label created on Run-time CF C# -
i create label "label1" dynamically in method. when click button want remove label created if write controls.remove(label1) says control doesn't exist in context. how achieve this?
edit: following jon suggestion implemented foreach loop doesn't anything. code, panel use created design:
void generatecontrols() { label labelone = new label(); button btncontinue = new button(); panel.suspendlayout(); suspendlayout(); //btncontinue btncontinue.backcolor = system.drawing.color.black; btncontinue.forecolor = system.drawing.systemcolors.menu; btncontinue.location = new system.drawing.point(145, 272); btncontinue.name = "btncontinue"; btncontinue.size = new system.drawing.size(95, 28); btncontinue.tabindex = 13; btncontinue.text = "continue"; btncontinue.visible = true; controls.add(btncontinue); btncontinue.click += new system.eventhandler(btncontinue_click); //labelone labelone.location = new point(0,65); labelone.size = new system.drawing.size(100,20); labelone.text = "labelone"; labelone.name = "labelone"; labelone.visible = true; labelone.textchanged += new system.eventhandler(this.lbl_textchanged); labelone.backcolor = system.drawing.color.palegreen; controls.add(labelone); //panel panel.controls.add(labelone); panel.visible = true; panel.location = new point(0,0); panel.size = new size(240, 320); // controls.add(panel); panel.resumelayout(); resumelayout(); } and in when click on btncontinue:
private void btncontinuar_click(object sender, eventargs e) { foreach (control control in panel.controls) { if (control.name == "labelone"){ panel.controls.remove(control); break; } } } i debug , in panel.control continues if empty panel. help!
i suspect says variable doesn't exist in context. you'll have find label text, or knowing else it. example, when create set name property , find when want remove it:
panel.controls.removebykey("yourlabelname"); edit: noted in comments, removebykey doesn't exist in compact framework. you'd either have remember reference (in case don't need name) or use like:
foreach (control control in panel.controls) { if (control.name == "yourlabelname") { panel.controls.remove(control); break; } } edit2: , make more "generic" , desktop compatible, keep removebykey call , add app:
public static class formextensions { public static void removebykey(this control.controlcollection collection, string key) { if(!removechildbyname(collection, key)) { throw new argumentexception("key not found"); } } private static bool removechildbyname( control.controlcollection collection, string name) { foreach (control child in collection) { if (child.name == name) { collection.remove(child); return true; } // nothing found @ level: recurse down children. if (removechildbyname(child.controls, name)) { return true; } } return false; } }
Comments
Post a Comment