Display Images in GridView from folder in ASP.NET

We need to display images in GridView control from a folder in ASP.NET. This is really very simple task.

Gridview is very rich control and easy to use. The GridView control is a powerful data grid control that allows you to display an entire collection of data, sorting, paging, and perform inline editing.

Display images in GridView from folder - Example

In the following example we will see how to upload image to folder and display the uploaded images in GridView control.

Web form

  1. <h3>Display images in gridview from folder</h3>  
  2. <table>  
  3.     <tr>  
  4.         <td>  
  5.             File:  
  6.         </td>  
  7.         <td>  
  8.               <asp:FileUpload ID="fupload" runat="server" />  
  9.         </td>  
  10.     </tr>  
  11.     <tr>  
  12.         <td>  
  13.               
  14.         </td>  
  15.         <td>  
  16.             <asp:Button ID="btnUpload" runat="server" cssClass="button"   
  17.              Text="Upload Selected File" onclick="btnUpload_Click" />  
  18.         </td>  
  19.     </tr>  
  20. </table>  
  21.  <asp:GridView ID="Gv_imgs" CssClass="grid" runat="server" AutoGenerateColumns="false" ShowHeader="false">  
  22.       <Columns>  
  23.            <asp:BoundField DataField="Text" HeaderText="Name" />  
  24.             <asp:ImageField DataImageUrlField="Value" ControlStyle-Height="75" ControlStyle-Width="75" HeaderText="Images" />  
  25.       </Columns>  
  26.  </asp:GridView>  
C#-code behind

 

Import the following namespace
using System.IO;

  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     if (!IsPostBack)  
  4.     {  
  5.         string[] ImagePaths = Directory.GetFiles(Server.MapPath("~/Images/"));  
  6.         List<ListItem> Imgs = new List<ListItem>();  
  7.         foreach (string imgPath in ImagePaths)  
  8.         {  
  9.             string ImgName = Path.GetFileName(imgPath);  
  10.             Imgs.Add(new ListItem(ImgName, "~/Images/" + ImgName));  
  11.         }  
  12.         Gv_imgs.DataSource = Imgs;  
  13.         Gv_imgs.DataBind();  
  14.     }  
  15. }  
  16. protected void btnUpload_Click(object sender, EventArgs e)  
  17. {  
  18.     if (fupload.HasFile)  
  19.     {  
  20.         string fileName = fupload.FileName;  
  21.         fupload.PostedFile.SaveAs(Server.MapPath("~/Images/") + fileName);  
  22.         Response.Redirect(Request.Url.AbsoluteUri);  
  23.     }  
  24. }  

 

Output