Using Button Command event in ASP.NET


Two major events of asp.net button server control are OnClick and OnCommand events. Both are triggered when you click on button control.  On sequence, first OnClick and then OnCommand event is executed.

  1. <%@ Page Language="C#" %>
  2.  
  3. <script runat="server">
  4.     
  5.     protected void Button_Command(object sender, CommandEventArgs e)
  6.     {
  7.         if (e.CommandArgument == "FirstButton")
  8.         {
  9.             Label1.Text = "You clicked on First Button";
  10.  
  11.         }
  12.         else if (e.CommandArgument == "SecondButton")
  13.         {
  14.             Label1.Text = "You clicked on Second Button";
  15.         }
  16.     }
  17.  
  18. </script>
  19.  
  20. <html xmlns="http://www.w3.org/1999/xhtml">
  21. <head runat="server">
  22.     <title>Button Command event in asp.net</title>
  23. </head>
  24. <body>
  25.     <form id="form1" runat="server">
  26.     <div>
  27.         <br />
  28.         <asp:Label ID="Label1" runat="server"></asp:Label>
  29.         <br />
  30.         <br />
  31.         <br />
  32.         <asp:Button ID="Button1" runat="server" Text="First Button" OnCommand="Button_Command"
  33.             CommandArgument="FirstButton" />
  34.         &nbsp; &nbsp;
  35.         <asp:Button ID="Button2" runat="server" Text="Second Button" OnCommand="Button_Command"
  36.             CommandArgument="SecondButton" />
  37.     </div>
  38.     </form>
  39. </body>
  40. </html>