代码之家  ›  专栏  ›  技术社区  ›  Andree643

如何为ImageButton程序添加EventHandler OnCommand?

  •  2
  • Andree643  · 技术社区  · 14 年前

    我有代码,在代码中我将imagebutton以编程方式添加到表中,我需要将事件处理程序分配给这个imagebutton。当我编写ASP/HTML代码时,命令中有属性oncommand,但在c中,没有类似的属性。只有commandname和commandattribute。

    ImageButton ib = new ImageButton
                         {
                             CommandName = "Edit",
                             CommandArgument = id.ToString(),
                             ImageUrl = "~/Images/icons/paper_pencil_48.png",
                             AlternateText = "Edit document"
                         };
    
    3 回复  |  直到 11 年前
        1
  •  2
  •   Samu Lang    14 年前

    在ASP.NET中,属性名为“on”+事件名。

    在C中,它只是事件的名称: Command .

    假设您在页面加载时添加了图像按钮:

    protected void Page_Load(object sender, EventArgs e)
    {
        int id = 0;
        ImageButton ib = new ImageButton
        {
            CommandName = "Edit",
            CommandArgument = id.ToString(),
            ImageUrl = "~/Images/icons/paper_pencil_48.png",
            AlternateText = "Edit document"
        };
        ib.Command += ImageButton_OnCommand;
    
        form1.Controls.Add(ib);
    }
    

    这是你的答案,正如DTB所说:

    ib.Command += ImageButton_OnCommand;
    

    然后您就有了事件处理程序本身,只是为了完成:

    void ImageButton_OnCommand(object sender, EventArgs e)
    {
        // Handle image button command event
    }
    
        2
  •  1
  •   dtb    14 年前

    无法使用对象初始值设定项语法添加事件处理程序。您需要单独添加它们:

    ImageButton ib = new ImageButton { ... };
    ib.Command += ImageButton_Command;
    
        3
  •  0
  •   Genius    14 年前

    ib.命令+=

    伙计在那行后面添加这个代码,然后点击标签两次,你的工作就完成了。

    推荐文章