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"
开发者_如何学C };
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
}
Event handlers cannot be added with object initializer syntax. You need to add them separately:
ImageButton ib = new ImageButton { ... };
ib.Command += ImageButton_Command;
ib.Command +=
Buddy add this code after that line, and click tab two consegetive times, your work is done.
精彩评论