开发者

Add Event Handler from String [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 开发者_如何转开发11 years ago.

Hi all I have a button and I know it has a "Click" event. How Can I add this event with "Click" and Delegate? Thanks


Define helper method:

public static void AddEventHandler(object obj, string eventName, Delegate handler)
{
    if(obj == null) throw new ArgumentNullException("obj");
    if(eventName == null) throw new ArgumentNullException("eventName");
    if(handler == null) throw new ArgumentNullException("handler");

    var type = obj.GetType();
    var evt = type.GetEvent(eventName);
    if(evt == null) throw new ArgumentException(
        string.Format("Event '{0}' is not defined by type '{1}'", eventName, type.Name));

    evt.AddEventHandler(obj, handler);
}

and use it:

AddEventHandler(yourButton, "Click", yourHandlerDelegate);


In the .cs file related to your form (Web Form, Win Form)::

// This will handle the event for the button named bntSubmit
protected void btnSubmit_Click(object sender, EventArgs e)
{
   // Code to handle click event
}

Generally speaking, most people (but not all) use the <controlid>_<event> naming convention for event handlers. Like btnSumbit_Click for the OnClick event for a button with an id of btnSubmit.

For ASP.NET, you'll need to set the buttons OnClick attribute in the markup (.aspx file) (double-clicking on the form in the designer will also generate the stub):

<asp:Button ID="btnSubmit" OnClick="btnSubmit_Click" Text="Submit" runat="server" />

In Win Forms, double-clicking the button on the designer is the quickest way to generate the method stub.

I haven't worked much in MVC or WPF, but I'd imagine the process is similar, and the method signatures are the same.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜