Bind Runtime Image in ASP.net


I was facing issue on dynamic binding image on page. Actually the scenario was users uploads the image depends on them how many they uploads. On front-end I wanted to show the images uploaded by the users, I don’t want to use any heavy aso.net control the reason behind it can be one or two images also.

I thought if I bind images in my html Image control with source, It would be very helpful. I found the solution it’s very easy and really fast. Here is the code:

.aspx page:

Below I have used a Div control with runat server attribute to make server control to bind the runtime image(s).

<div id="divImg" runat="server">div>

.aspx.cs

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //bind uploaded files from upload directory
            BindUploadFiles();
        }
    }

   protected void BindUploadFiles()
    {
//the path of directory where your uploaded images belong
        DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/Upload/"));

//get the all uploaded images

        FileInfo[] fi = di.GetFiles("*", SearchOption.AllDirectories);

        foreach (FileInfo fileExistInDir in fi)
        {

//declare Html Image Control for each images

            HtmlImage img = new HtmlImage();
            ddlUploadedFiles.Items.Add(fileExistInDir.Name);

//bind the image source with image control

            img.Src = "Upload/" + fileExistInDir.Name;
            img.Width = 150;
            img.Height = 100;
  img.Style.Add("padding", "5px");    //for image padding
img.Style.Add("border", "solid 1px Green"); //image border
//Add image control (child) with parent (div) control

            divImg.Controls.Add(img);
        }
    }

And finaly press F5 to run the application. See how it displays.

Comments