tags:

views:

98

answers:

2

What is the proper way to fire an ASP.NET control event programatically? I am looking to refactor a little code and I see items sprinkled in the code behind coded like this; the developer is calling the event handler and saturating it with params. for a DropDownList

ddlAddress.SelectedIndex = 1;
ddlAddress_SelectedIndexChanged(null, new EventArgs());

& for a RadioButtonList

rblAction.SelectedIndex = 0;
rblActionType_SelectedIndexChanged(null, new EventArgs());

Is this normal coding practice? What should I do as to not disrupt/break the page? Any thoughts or suggestions would be appreciated.

Thanks, ~ck in San Diego

+5  A: 

I would start by removing all of the code from the actual event's method and refactor it into a new method called AddressChanged or whatever else fits your naming standards. You can then call that new function from anywhere else in your code.

protected void ddlAddress_SelectedIndexChanged(object sender, EventArgs e){
    AddressChanged();
}
private void AddressChanged(){
    //do the changed event
}

private void doingSomething(){
    ddlAddress.SelectedIndex = 1;
    AddressChanged();
}
RSolberg
+1 This is much better written than mine. Nicely done!
Andrew Hare
@Andrew: lol, thanks...
RSolberg
A: 

Note that you're calling the event handler programatically, not the event.

This can be indicative of a design problem, because usually event handlers should not be relying on each other to execute in a specific order. However, I have seen this pattern and even used it occasionally when code that existed in one event handler needed to be executed in another event handler and could not be refactored at that time. You can set the "sender" to indicate that it's coming from elsewhere in the code and not from the expected control itself, but this is a little bit too opaque to be called a good design.

It would be better practice to refactor out the code that needed to be shared, and put it in a private method, and have both event handlers use it, passing in whatever data from the sender or the eventargs that it needed.

womp