简体   繁体   English

以编程方式触发ASP.NET控件事件的正确方法是什么?

[英]What is the proper way to fire an ASP.NET control event programatically?

What is the proper way to fire an ASP.NET control event programatically? 以编程方式触发ASP.NET控件事件的正确方法是什么? 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 为DropDownList

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

& for a RadioButtonList &为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 谢谢,〜ck在圣地亚哥

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. 我将首先从实际事件的方法中删除所有代码,然后将其重构为一个名为AddressChanged或符合您的命名标准的新方法。 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();
}

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. 最好将需要共享的代码重构,并将其放在私有方法中,并让两个事件处理程序都使用它,从发送方或需要的eventargs传入任何数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM