【问题标题】:e.CommandArgument for asp button is not workinge.CommandArgument for asp 按钮不起作用
【发布时间】:2011-08-06 07:19:20
【问题描述】:

我正在使用 C# 开发一个 asp.net 应用程序。 我创建了一个 .aspx 页面,并在页面的不同位置放置了四个按钮。 在服务器端,我只想为所有四个按钮使用一次单击事件。

这是我的代码:

aspx 页面

<asp:Button ID="Button1" runat="server" CommandArgument="Button1" onClick = "allbuttons_Click" />
<asp:Button ID="Button2" runat="server" CommandArgument="Button2" onClick = "allbuttons_Click" />
<asp:Button ID="Button3" runat="server" CommandArgument="Button3" onClick = "allbuttons_Click" />
<asp:Button ID="Button4" runat="server" CommandArgument="Button4" onClick = "allbuttons_Click" />

cs页面

protected void allbuttons_Click(object sender, EventArgs e)
{
    //Here i want to know which button is pressed
    //e.CommandArgument gives an error
}

【问题讨论】:

  • e.CommandArgument 没有意义...你确定你指的不是(sender as Button).CommandArgument
  • 我只想知道按下了哪个按钮。我想获取按下按钮的命令参数。

标签: asp.net commandargument aspbutton


【解决方案1】:

使用

OnCommand = 

protected void allbuttons_Click(object sender, CommandEventArgs e) { }

【讨论】:

    【解决方案2】:

    您可以将命令文本分配给您的按钮,如下所示:

    protected void allbuttons_Click(Object sender, CommandEventArgs e) {
        switch(e.CommandName) {
            case "Button1":
                Message.Text = "You clicked the First button";
                break;
            case "Button2":
                Message.Text = "You clicked the Second button";
                break;
            case "Button3":
                Message.Text = "You clicked Third button";
                break;
            case "Button4":
                Message.Text ="You clicked Fourth button";
                break;
        }
    }
    

    【讨论】:

      【解决方案3】:

      实际上,您根本不需要传递 CommandArgument 即可知道您按下了哪个按钮。您可以像下面这样获取按钮的 ID:

      string id = ((Button)sender).ID;
      

      【讨论】:

        【解决方案4】:

        @Tejs 在他的评论中是正确的,看起来你想要这样的东西:

        protected void allbuttons_Click(object sender, EventArgs e)
        {
            var argument = ((Button)sender).CommandArgument;
        }
        

        【讨论】:

          猜你喜欢
          • 2015-06-23
          • 1970-01-01
          • 2011-04-13
          • 2019-11-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多