ASP.Net Button Click Event

Updated on 26 Jun 2012,
Published on 25 Sep 2009

The ASP.Net Button click event is raised when it is being clicked by the user. This event of Button control submits the web form data to the server and performs the specified action there. The click event is commonly used when the ASP.Net Button has no command name associated with it and is placed as a submit button on the web page to send the user input to the server using HTML Post method. In ASP.Net each web server control has its own set of events that can be raised and handled at server side. The Button server control has OnClick method that can be used to trap the click event. It allows you to handle the event without attaching a delegate. 

Button Control Examples:

You can see the live samples and examples of Button Control from the following links:

Attaching Click Event with Button Control

There are 2 ways for attaching the OnClick event handler with ASP.Net Button control:

1. Double clicking the button control in design view of web page while working in Visual Web Developer. By default it will generate the code for OnClick event of that Button as follows:

<asp:Button ID="Button1" 
    runat="server" 
    Text="Button" 
    OnClick="Button1_Click" />
protected void Button1_Click(object sender, EventArgs e)
{

}

2. You can also attach the event programmatically using server code at Page_Load event of web page as follows:

protected void Page_Load(object sender, EventArgs e)
{
    Button1.Click += new EventHandler(Button1_Click);
}

protected void Button1_Click(object sender, EventArgs e)
{
    throw new Exception("The method or operation is not implemented.");
}

For attaching the event programmatically write the ID of the button control inside the Page_Load event, as "Button1" used in above sample code. Next use the dot operator to open the intellisense showing properties and methods available for it and select the Click event from the list. Then add "+=" and press tab to auto generate the handler code for it. You will get the code similar to the sample code show above.

Example for ASP.Net Button Click

HTML Code
<asp:Button ID="Button1" 
    runat="server" 
    Text="Button" 
    OnClick="Button1_Click" />
C# Code:
protected void Button1_Click(object sender, EventArgs e)
{
    Button1.Text = "You clicked this button.";
}

Output:

Get the output for above discussed code from the following link:

Button Click Event

Continue to the next tutorial: ASP.Net Button Command Event to learn how to use the CommandName property and CommandArgument property of ASP.Net Button control using OnCommand method.

2 Responses to "ASP.Net Button Click Event"
srinivas
very good
Hello there, I'm newbie in asp. Thank's for the tutorial, it's simple and useful. :)
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email