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
- <h3>Display images in gridview from folder</h3>
- <table>
- <tr>
- <td>
- File:
- </td>
- <td>
- <asp:FileUpload ID="fupload" runat="server" />
- </td>
- </tr>
- <tr>
- <td>
-
- </td>
- <td>
- <asp:Button ID="btnUpload" runat="server" cssClass="button"
- Text="Upload Selected File" onclick="btnUpload_Click" />
- </td>
- </tr>
- </table>
- <asp:GridView ID="Gv_imgs" CssClass="grid" runat="server" AutoGenerateColumns="false" ShowHeader="false">
- <Columns>
- <asp:BoundField DataField="Text" HeaderText="Name" />
- <asp:ImageField DataImageUrlField="Value" ControlStyle-Height="75" ControlStyle-Width="75" HeaderText="Images" />
- </Columns>
- </asp:GridView>
C#-code behind
Import the following namespace
using System.IO;
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- string[] ImagePaths = Directory.GetFiles(Server.MapPath("~/Images/"));
- List<ListItem> Imgs = new List<ListItem>();
- foreach (string imgPath in ImagePaths)
- {
- string ImgName = Path.GetFileName(imgPath);
- Imgs.Add(new ListItem(ImgName, "~/Images/" + ImgName));
- }
- Gv_imgs.DataSource = Imgs;
- Gv_imgs.DataBind();
- }
- }
- protected void btnUpload_Click(object sender, EventArgs e)
- {
- if (fupload.HasFile)
- {
- string fileName = fupload.FileName;
- fupload.PostedFile.SaveAs(Server.MapPath("~/Images/") + fileName);
- Response.Redirect(Request.Url.AbsoluteUri);
- }
- }
Output