2

I have code, where i add ImageButton to table programaticly and I need to assign event handler to this ImageButton. When I write ASP/HTML code, there is attribute OnCommand, but in C#, there is nothing like this. Just CommandName and CommandAttribute.

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

3 Answers 3

2

In ASP.NET the attribute is named "On" + name of event.

In C# it's the name of the event only: Command.

So let's say you're adding the image button on page load:

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);
}

This is your answer, just like dtb says:

ib.Command += ImageButton_OnCommand;

And then you have the event handler itself, just to be complete:

void ImageButton_OnCommand(object sender, EventArgs e)
{
    // Handle image button command event
}
Sign up to request clarification or add additional context in comments.

Comments

1

Event handlers cannot be added with object initializer syntax. You need to add them separately:

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

Comments

0

ib.Command +=

Buddy add this code after that line, and click tab two consegetive times, your work is done.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.