Iβm really confused. π. In ASP.NET, to capture a click event in C#, would I use runat="server" and onclick="emnt_Click()", or elmt.onclick = elmt_Click(), or elmt.Attributes.Add("onclick","elmt_Click()", or just have this:
private void elmt_Click()
{
// Code
}
Do they all work?
Iβm really confused. π
Please help :):):)
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & Iβll get back to you as soon as possible.
Method 1
In your aspx page you can hook up an onclick event with OnClick="elmt_Click" (provided itβs inside a form). For example:
<asp:Button ID="btn" runat="server" OnClick="elmt_Click" Text="Submit" />
Alternatively in your code behind file, you can hook up the onclick event by adding the following in your page_load method:
elmt_Click.Click += elmt_Click; // Note the Plus and equal sign
In your code behind you can the create the event as:
protected void elmt_Click(object sender, EventArgs e)
{
}
The onclick event needs to be accessible to the aspx page. Therefore private will need to be changed to protected or public. Also the method will need to pass in sender and EventArgs.
elmt.Attributes.Add() will only add a html attribute to a tag and will not wire up an ASP.NET event.
Documentation for ASP.NET button can be found at https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.button.onclick?view=netframework-4.8
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0