Search code examples
c#asp.netstaticevent-handlingstatic-methods

Reference static method for ASP.NET/C# event handler


I have a button an my ASP.NET page which currently looks like this:

<asp:Button ID="Button1" Text="Click me" />

I want to attach an event handler to the button. Normally, that would look like this:

<asp:Button ID="Button1" Text="Click me" OnClick="SomeFunction" />

However, in this case, the method I want to reference is static; that is, I can only call it from Namespace.Class.Method rather than ClassInstance.Method, When I try the following, I get an error:

<asp:Button ID="Button1" Text="Click me" OnClick="Namespace.Class.Method" />

So, how can I use this method as an event handler? Unfortunately, I do not have control over the namespace. I would prefer to use some ASP.NET technique rather than a C# technique, because I am more familiar with ASP.NET.


Solution

  • Event handlers can also be added, removed and edited in the code behind. For example:

    asp:

    <asp:Button ID="Button1" Text="Click me" />
    

    code behind:

    Button1.Click += new EventHandler(Namespace.Class.Method);
    

    note that Method should take (object sender, EventArgs e) as its arguments