vijay

welcome Netizen

Share Your Knowledge.It is a way to achieve immortality

Tuesday, March 20, 2012

Display images from the folder in asp.net



This seems to be common question..How to show a image directly from the folder..Instead of saving a images to database,
Normally we want to display all the images from the particular folder in asp.net..Then we follow easy process to give the image link to the image control dynamically.

In normal case we store the images in database then we retrieve it and show the images. But this process is totally different process. Just we get all the Images form the folder itself..In a previous post i discussed the way to store image URL or direct image in database. For you reference i mention the link as below


  
Here its easy code to show your image form folder..

Code:
if (!IsPostBack)
        {
            DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/images"));
            int i = 0;
            foreach (FileInfo fi in di.GetFiles())
            {
                //HtmlInputImage ib = new HtmlInputImage();
                Image ib = new Image();
                ib.ID = "ImageButton" + i;
               
                i++;
                ib.ImageUrl  = Server.MapPath("~/images")+"\\" + fi.Name;
                ib.Attributes.Add("onclick", "javascript:window.open('" +"../images/" + fi.Name + "');return false;");
                Placeholder1.Controls.Add(ib);
                Literal lit1 = new Literal();
                lit1.Text = "<br/>";
                Placeholder1.Controls.Add(lit1);
                         }

 Grid view:
Incase if you need to bind the image in grid view follow the below code.
DataTable dt = new DataTable();
            dt.Columns.Add("img");
            foreach (FileInfo fi in di.GetFiles())
            {
                DataRow dr = dt.NewRow();
                dr["img"] = Server.MapPath("~/images") + "\\" + fi.Name;
                dt.Rows.Add(dr);
            }
            GridView1.Datasource = dt;
            GridView1.Databind();

I hope you like this article …

0 comments:

Post a Comment