Monday, August 30, 2010

Use Button CommandName, CommandArgument Property to dynamically Call Button Command Events

Button Server Control has two types: submit and command. By default a button is a submit button which doesn't have commandname, commandArguments, and it has button.Click events as the default event. We can create command button using the following steps.

Create a Web Application, in the designer drag 4 buttons:

Set the CommandName Property to be: btn1Command, btn2Command, btn3Command, btn4Command. And CommandArgument to be: Asc, Desc, Upper, Lower.

The Source is like:

< body>
< id="form1" runat="server" method="post" action="Default.aspx">
  < id="Button1" runat="server" commandname="btn1Command" text="NAsc" commandargument="Asc">
   < id="Button2" runat="server" commandname="btn2Command" text="NDesc" commandargument="Desc">
   < id="Button3" runat="server" commandname="btn3Command" text="LUpper" commandargument="Upper">
   < id="Button4" runat="server" commandname="btn4Command" text="LLower" commandargument="Lower">
  < /form>
< /body>

In the Events window, set these 4 buttons Command to be: Button_Command, double click, and write in the Button_Command Event the following code:

protected void Button_Command(object sender, CommandEventArgs e)
{
 switch (e.CommandName)
 {
   case "btn1Command":
   ShowNumbers(e.CommandArgument);
   break;
   case "btn2Command":
   ShowNumbers(e.CommandArgument);
   break;
   case "btn3Command":
   ShowLetters(e.CommandArgument);
   break;
   case "btn4Command":
   ShowLetters(e.CommandArgument);
   break;
  }
}

And Write the ShowNumbers, ShowLetters Methods:

private void ShowNumbers(object commandArgument)
{
  if (commandArgument.ToString() == "Asc")
  {
   Response.Write("123");
  }
  else if (commandArgument.ToString() == "Desc")
  {
   Response.Write("321");
  }
}

private void ShowLetters(object commandArgument)
{
  if (commandArgument.ToString() == "Upper")
  {
   Response.Write("AAA");
  }
  else if (commandArgument.ToString() == "Lower")
  {
   Response.Write("aaa");
  }
}

Build the web application to test the button commands. The sample code is at:

http://groups.google.com/group/jiezhu0815myfiles/web/ButtonCommandSample.rar

No comments: