Add Event Handler from String [closed]
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.
精彩评论