简体   繁体   中英

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.

you can run it this way;

asp.net code,

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

c# code,

private void btn1_Click(object sender, EventArgs e)
{
   Namespace.Class.Method();
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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