c# - LinkLabel Click event being overwritten within loop -
here's sample code denotes problem. adds 5 linklabel
s, each click
event handler. text on label 1...5 , should display same result when clicked, when click on each of labels same message each: 5.
it's lastly handler overwriting handler on each of other labels. thought had avoided creating new eventhandler
, new linklabel
each iteration of loop.
i added each linklabel
flowlayoutpanel
.
why getting result, , how can prepare it?
list<test> objects = new list<test>(); (int = 0; < 5; i++) { objects.add(new test(i + 1)); } foreach (test t in objects) { linklabel label = new linklabel(); label.autosize = true; label.text = t.a + ""; label.click += new eventhandler((sender, args) => { messagebox.show(t.a + ""); }); flowlayoutpanel1.controls.add(label); }
in effort reproduce problem described code, link labels 1 through 5 displayed 1 through 5 respectively when clicked want.
here standalone illustration minimally builds upon code posted (just extent necessary create build , run)...and works expected:
// fornow: added main method poc. void main() { // fornow: added necessary form , flowlayoutpanel locals. form form1 = new form(); flowlayoutpanel flowlayoutpanel1 = new flowlayoutpanel(); list<test> objects = new list<test>(); (int = 0; < 5; i++) { objects.add(new test(i + 1)); } foreach (test t in objects) { linklabel label = new linklabel(); label.autosize = true; label.text = t.a + ""; label.click += new eventhandler((sender, args) => { messagebox.show(t.a + ""); }); flowlayoutpanel1.controls.add(label); } // fornow: added necessary command wiring , display call. form1.controls.add(flowlayoutpanel1); form1.show(); } // fornow: added test class based on op's code. public class test { public int { get; set; } public test(int a) { this.a = a; } }
you may have problem in other code employing, code shared works fine based on said expect.
c# winforms handler linklabel
No comments:
Post a Comment