Dynamically create an ImageButton

asp.net, c#

Solution

Take a look at this answer, it is related with dynamic controls and events

As Jon commented you cannot add a string to the event, in this case you need to add a handler for the event:

    protected void Page_Init(object sender, EventArgs e)
    {
        var i = new ImageButton();
        i.Click += new ImageClickEventHandler(i_Click);
        this.myPanel.Controls.Add(i);
    }

    void i_Click(object sender, ImageClickEventArgs e)
    {
        // do something
    }

Alternativeley

    protected void Page_Init(object sender, EventArgs e)
    {
        var i = new ImageButton();
        i.Click += (source, args) =>
        {
            // do something
        };
        this.myPanel.Controls.Add(i);
    }

Problem

I’m trying to dynamically declare an ImageButton. I declare it and assign an ID and Image to it as follows: ``` ImageButton btn = new ImageButton(); btn.ImageUrl = "img/Delete.png"; btn.ID = oa1[i] + "_" + i; btn.OnClick = "someMethod"; ``` But when I try to assign an OnClick handler for the button it throws the following exception: ``` System.Web.UI.WebControls.ImageButton.OnClick is inaccessible due to protection level ```

Original source