asp.net - How to use Button Command event

Button Command event
The Button web server control displays a push button control on the Web page. The Button lets users post a page to the server. The control triggers an event in server code that asp.net developers can handle to respond to the postback. The Button can also raise an event in the client script that developers can handle before the page is posted or that can run and then cancel the submission of the page.

The following asp.net c# tutorial code demonstrates how we can use the Button Command event. To trigger a command event, the asp.net c# developers have to set the Button control’s OnCommand() method and CommandName property value.

The Button Command event occurs when the Button control is clicked. The Command event is raised when the Button web server control is clicked. The Command event is commonly used when a command name such as Delete, is associated with the Button control. This allows developers to create multiple Button controls on a Web page (such as delete, add, and update Buttons) and programmatically determine which Button control is clicked.

The Button control’s CommandName property gets or sets the command name associated with the Button control that is passed to the Command event. This property value is a String which is the command name of the Button control. The default value is Empty. When the asp.net developers have multiple Button controls on a web page, they have to use the CommandName property to specify or determine the command name associated with each Button control.

The Button OnCommand() method raises the Command event of the Button control. The Command event is raised when the Button control is clicked.
ButtonCommandNameExample.aspx

<%@ Page Language="C#" %>

<!DOCTYPE html>

<script runat="server">
    protected void Button_Command(Object sender, System.Web.UI.WebControls.CommandEventArgs e) { 
        switch(e.CommandName)
        {
            case ("CheckedNow"):
                CheckBox1.Checked = true;
                break;
            case ("UnCheckedNow"):
                CheckBox1.Checked = false;
                break;
        }
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>asp.net Button example: how to use OnCommand and CommandName property</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Fuchsia">Using CommandName property</h2>
        <asp:CheckBox ID="CheckBox1" runat="server" Text="Click the button for checked or unchecked" ForeColor="Red" />
        <br /><br />
        <asp:Button ID="Button1" runat="server" Text="Check Now" OnCommand="Button_Command" CommandName="CheckedNow" Font-Bold="true" ForeColor="Teal" />
        <asp:Button ID="Button2" runat="server" Text="UnCheck Now" OnCommand="Button_Command" CommandName="UnCheckedNow" Font-Bold="true" ForeColor="Teal" />
    </div>
    </form>
</body>
</html>


Related asp.net example