Home   Cover Cover Cover Cover
 

Command Events for Buttons


From Section 6.4.3 of the book

A click on a button normally raises a Click event. However, if there are multiple buttons on a page it can be useful to raise a Command event instead of a Click event. A Command event has a certain command name by which the buttons can be distinguished. This makes it possible to handle clicks on all of the buttons in a single event handler:

ButtonCommands.aspx
<%@ Page Language="C#" %>
<html>
  <head>
    <script Language="C#" Runat="server">
      void ButtonClick(object sender, CommandEventArgs e) {
        text.ForeColor = System.Drawing.Color.FromName(e.CommandName);
      }
    </script>
  </head>
  <body>
    <form Runat="server">
      <asp:Label ID="text" Text="Sample text" Runat="server" /><br><br>
      <asp:Button Text="Red" CommandName="Red" OnCommand="ButtonClick" Runat="server" />
      <asp:Button Text="Blue" CommandName="Blue" OnCommand="ButtonClick" Runat="server" />
      <asp:Button Text="Green" CommandName="Green" OnCommand="ButtonClick" Runat="server" />
    </form>
  </body>
</html>

Try it

   http://dotnet.jku.at/book/samples/6/ButtonCommands.aspx