Nishantha
Nishantha

Reputation: 6695

How to dynamically generate imagebutton in div in ASP.net web application using C#?

I'm using this code to dynamically generate imagebutton when retrieve images in img folder in ASP.net Web Application Project.

private void OpenImage()
{
    foreach (string strFileName in Directory.GetFiles(Server.MapPath("~/img/")))
    {
          ImageButton imageButton = new ImageButton();
          FileInfo fileInfo = new FileInfo(strFileName);
          imageButton.ImageUrl = "~/img/" + fileInfo.Name;
          imageButton.Width = Unit.Pixel(100);
          imageButton.Height = Unit.Pixel(100);
          imageButton.Style.Add("padding", "10px");
          imageButton.Click += new ImageClickEventHandler(imageButton_Click);
          Panel1.Controls.Add(imageButton);
     }
 }

Now I want to display this within div tag that also generate dynamically. Any Suggestions Guys?

Upvotes: 0

Views: 3297

Answers (1)

p.s.w.g
p.s.w.g

Reputation: 149040

You can create a <div> (or any plain HTML element) in code behind with the HtmlGenericControl class, and use that to wrap your ImageButton any way you want. For example:

private void OpenImage()
{
    foreach (string strFileName in Directory.GetFiles(Server.MapPath("~/img/")))
    {
        ImageButton imageButton = new ImageButton();
        ...
        HtmlGenericControl div = new HtmlGenericControl("div");
        div.Attributes["class"] = "my-class"; // or div.Attributes.Add("class", "my-class"); 
        div.Controls.Add(imageButton);
        Panel1.Controls.Add(div);
    }
}

Upvotes: 3

Related Questions