tags:

views:

44

answers:

4

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" };
A: 

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

ImageButton ib = new ImageButton { ... };
ib.Command += ImageButton_Command;
dtb
A: 

ib.Command +=

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

Subodh Bansal
A: 

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
}
langsamu
Great, thanks guys. ;)
Andree643
A: 

This is not an answer, but more of a question (I can't add comments because I don't have enough points)

What happens when button adding happens in a class, but the function is in the main class of the page? How do I refer to it?

I get a "does not exist in the current context" error and can't compile the code. Any ideas?

Cristian
Best to post your question as a new question. StackOverflow is not a traditional forum. You pose a question, people give answers, and then you mark one answer as the best answer for you. Just click the 'Ask Question' button in the top right of StackOverflow. Give as many details as necessary, and you should find you get an answer rather quickly.
Peter
Thanks for pointing that out. I think StackOverflow is rather intuitive, but for example, I don't know how to add a question that is related to this question, or something like that. I just wanted to not overcrowd the SO with too many related questions.
Cristian