Dynamically create an ImageButton

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You couldn’t assign a value to a method like that, even if it were accessible. You need to subscribe to the event:

btn.Click += ClickHandlingMethod;

Method 2

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

Method 3

An example:

private void CreateAButton()
{
    var button = new ImageButton();
    button.ImageUrl = "yourimage.png";
    button.ID = "Button1";
    button.Click += ButtonClick;

    Page.Form.Controls.Add(button);
}

private void ButtonClick(object sender, ImageClickEventArgs e)
{
    // Do stuff here
    // ...
}

Method 4

You can use this code (one significant change) :

private void CreateAButton()
    {
        var button = new ImageButton();
        button.ImageUrl = "yourimage.png";
        button.ID = "Button1";           
        button.PostBackUrl = "http://www.towi.lt";
        Page.Form.Controls.Add(button);
    }

Trick is in “PostBackUrl”. If you write correct link it will redirects to it (as in example). In other cases this will add original server name, ‘/’ and text you entered. For example ‘xxx’ will be turned to “http://yourservername/xxx“. It is very useful, when you working with redirects to same ISS, but different sites and dynamically creating buttons for users.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x