Question

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?

Was it helpful?

Solution

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);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top