简体   繁体   中英

ASP.NET ImageButton Click event

I have a dynamic ImageButton and I want it to trigger a method when it's clicked. I have the following code, which unfortunatelly it's not working.

ImageButton imb = new ImageButton();
imb.Attributes.Add("runat", "server");
        imb.Click += new ImageClickEventHandler(ImageButton1_Click);
        imb.ID = "ID";
        imb.ImageUrl = "link to image";
Panel1.Controls.Add(imb);

protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
    //it should go here
}

you must add your ImageButton to a suitable continer.

eg:

 form1.Controls.Add(Imb);
 /// form1 must have runat=server

you can find useful tips at here .

Adding dynamic controls to the page is a tricky matter. Unfortunately, you cannot just declare an object of WebControl derived type and expect it to work.

In ASP.NET WebForms, there is a concept called Page Lifecycle . It is a broad matter, but my point is that there is a particular order you must obey to plug-in the dynamic control into the page. A practical example follows.

Start with dynamic control declaration at the class level.

protected ImageButton imb = null;

Then you initialize it durring the page initialization. One possibility is to handle the PreInit event.

protected void Page_PreInit(object sender, EventArgs e)
{
    imb = new ImageButton()
    {
        ID = "ID",
        ImageUrl = "link to image"
    };

    imb.Click += Imb_Click;

    Panel1.Controls.Add(imb);

}

private void Imb_Click(object sender, ImageClickEventArgs e)
{
    // Do your stuff
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        // Set initial properties as appropriate. E.g.
        imb.AlternateText = "...";
    }
}

You're good to go.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM