Command name : Command « ASP.net Controls « ASP.NET Tutorial






<%@ Page Language="C#" AutoEventWireup="true" CodeFile=Default.aspx.cs" Inherits="CommandTest" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Command Button Test</title>
</head>
<body>
   <form id="form1" runat="server">
   <div id="container">
      <h1>Simple Calculator</h1>
      <div class="box">
         <asp:TextBox ID="txtValue1" runat="server" />
         <asp:Button Text="+" runat="server" ID="btnAdd" Width="30px"
            OnCommand="Button_Command" CommandName="add" />
         <asp:Button Text="-" runat="server" ID="btnSubtract" Width="30px"
            OnCommand="Button_Command" CommandName="subtract" />
         <br/>
         <asp:TextBox ID="txtValue2" runat="server" />
         <asp:Button Text="*" runat="server" ID="btnMultiply" Width="30px"
            OnCommand="Button_Command" CommandName="multiply" />
         <asp:Button Text="/" runat="server" ID="btnDivide" Width="30px"
            OnCommand="Button_Command" CommandName="divide" />
      </div>
      <asp:Label ID="labMessage" runat="server" />
   </div>
   </form>
</body>
</html>

File: Default.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class CommandTest : System.Web.UI.Page
{

  protected void Button_Command(Object o, CommandEventArgs e)
  {
      double dVal1 = 0.0;
      double dVal2 = 0.0;

      bool val1okay = Double.TryParse(txtValue1.Text, out dVal1);
      bool val2okay = Double.TryParse(txtValue2.Text, out dVal2);

     if (val1okay && val2okay)
     {
       double result = 0;

       string op = "";
       switch (e.CommandName)
       {
         case "add":
           op = "+";
           result = dVal1 + dVal2;
           break;
         case "subtract":
           op = "-";
           result = dVal1 - dVal2;
           break;
         case "multiply":
           op = "*";
           result = dVal1 * dVal2;
           break;
         case "divide":
           op = "/";
           result = dVal1 / dVal2;
           break;
       }
       labMessage.Text = txtValue1.Text + op + txtValue2.Text + "=" + result;
     }
     else
     {
       labMessage.Text = "Unable to compute a value with these values";
     }
  }
  
}








3.40.Command
3.40.1.Handling the Command Event
3.40.2.Check CommandArgument (VB.net)
3.40.3.Command name