如何以编程方式为Image Button添加Event Handler OnCommand?

时间:2010-09-30 16:31:04

标签: c# asp.net

我有代码,我以编程方式将ImageButton添加到表中,我需要为此ImageButton分配事件处理程序。当我编写ASP / HTML代码时,有属性OnCommand,但在C#中,没有这样的东西。 Just CommandName和CommandAttribute。

ImageButton ib = new ImageButton
                     {
                         CommandName = "Edit",
                         CommandArgument = id.ToString(),
                         ImageUrl = "~/Images/icons/paper_pencil_48.png",
                         AlternateText = "Edit document"
                     };

3 个答案:

答案 0 :(得分:2)

在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
}

答案 1 :(得分:1)

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

ImageButton ib = new ImageButton { ... };
ib.Command += ImageButton_Command;

答案 2 :(得分:0)

ib.Command + =

Buddy在该行之后添加此代码,然后单击tab两个时间,您的工作就完成了。