c# - Where is the place to add custom arguments to button click? -
this can seems simple question ... crux how match button delegate signature void, object, eventargs
method or use event delegate.
as example, have code button changes color when it's clicked. however,
button1.click += new eventhandler(kk.changecolor);
carries eventargs button changecolor(object sender, eventargs e) method, meaningless rest of code use coloreventargs; ,
button1.click += delegate(object sender, eventargs e){ kk.changecolor(sender); };
doesn't allow later removal of delegate later in code.
so better? adding unnecessary parameters methods match button delegate or suffering not being able remove delegate later ?
or how change delegate signature of button? it seems there must 'cleaner' way this?
will appreciate advice.
"it seems there must 'cleaner' way this?"
in opinion, better design depends on changecolor
method do. if doing specific operation closely related event button clicked, leave real event handler method. means, should have required parameters match button.click
event handler signature (i don't think there option "change delegate signature") :
void changecolor(object sender, eventargs e) { messagebox.show("button {0} clicked!!!", ((button)sender).name); }
otherwise, if doing not only specific operation related event button clicked, refactor codes unrelated button click event method. way, other method doesn't need have unnecessary parameters. example :
void changecolor(object sender, eventargs e) { var buttonname = ((button)sender).name; messagebox.show("button {0} clicked!!! save form data", ); //assume form name can determined name of button being clicked saveformtodatabase(buttonname); } private void saveformtodatabase(string formname) { //save form specified in parameter }
Comments
Post a Comment