CommandName属性简介

3.5.2  CommandName属性

 

可以让窗体上的多个按钮来处理一个事件。我们可以标记按钮,使代码能根据窗体上单击的按钮进行逻辑判断。必须按照程序清单3-6给出的方式构建Button控件,这样才能利用多个按钮处理一个事件。

 

程序清单3-6  构建多个Button控件来处理一个函数

 

<asp:Button ID="Button1" runat="server" Text="Button 1" 

 OnCommand="Button_Command" CommandName="DoSomething1" /> 

<asp:Button ID="Button2" runat="server" Text="Button 2" 

 OnCommand="Button_Command" CommandName="DoSomething2" /> 

下面查看Button控件的这两个实例,需要注意几个地方。首先要注意的是哪个元素不存在,即具有OnClick事件的属性。相反,这里使用的是OnCommand事件,它指向Button_Command事件。这两个Button控件处理同一个事件。事件应该如何确定单击哪个按钮呢?可以通过CommandName属性的值来确定这一点。在这个例子中,它们拥有不同的值-- DoSomething1和DoSomething2。

 

下一步是创建这两个按钮要处理的Button_Command事件,方法是输入一个事件,或者在Visual Studio的代码视图中,从Button控件的可用事件下拉列表中选择Command事件。无论采用什么方法,都会得到如程序清单3-7所示的事件。

 

程序清单3-7  Button_Command事件

 

VB  

Protected Sub Button_Command(ByVal sender As Object,  

  ByVal e As System.Web.UI.WebControls.CommandEventArgs)  

          

   Select Case e.CommandName  

      Case "DoSomething1"  

         Response.Write("Button 1 was selected")  

      Case "DoSomething2"  

         Response.Write("Button 2 was selected")  

   End Select      

End Sub  

C#  

protected void Button_Command(Object sender,  

   System.Web.UI.WebControls.CommandEventArgs e)  

{  

   switch (e.CommandName)  

   {  

      case("DoSomething1"):  

         Response.Write("Button 1 was selected");  

         break;  

      case("DoSomething2"):  

         Response.Write("Button 2 was selected");  

         break;  

   }  

注意,这个方法使用的是System.Web.UI.WebControls.CommandEventArgs,而不是常用的System. EventArgs,以便把Select Case(switch)语句中使用的成员CommandName作为e.CommandName来访问。使用这个对象,可以检查窗体上被单击按钮使用的Command Name属性值,并根据该值执行特定的操作。

 

除了CommandName属性中定义的内容之外,还可以在Command事件中添加要传入的参数。为此,可以使用Button控件的CommandArgument属性。给属性添加值可以更精细地定义需要的项。在服务器端代码中使用CommandEventArgs对象中的e.CommandArgument,就可以获得这个值。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值