How to upload images to folder and display uploaded images in ASP.Net GridView using C#

Introduction

In this article, I will show you how to upload images to folder and display uploaded images in ASP.Net GridView using C#. I am using visual studio 2012 framework and Microsoft sql server 2008 R2 for this demo.

let’s start for this demo step by step using Asp.Net Empty Web site.

Step 1: Create Asp.Net project, by using following steps.

  1. Open Visual Studio.
  2. Click on File -> New -> Project.
  3. In this project, I am using C# as a programming language. In next debugging article I will show you how to upload multiple images using VB.NET
  4. Inside Visual C# -> Web -> Website -> Select Asp.Net Empty Web site -> Name your project as uploadimageinasp -> Select Ok

Step 2 : Index.aspx file.

Right click on your project -> Add -> new item -> Add Index.aspx file.

Now copy & paste following code in between form element of your Index.aspx.

<div>
        <br /><br />
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="Upload" />
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" ShowHeader="false">
    <Columns>
        <asp:BoundField DataField="Text" />
        <asp:ImageField DataImageUrlField="Value" ControlStyle-Height="100" ControlStyle-Width="100" />
    </Columns>
</asp:GridView>
    </div>

Step 3: Index.aspx.cs file.

Double click on upload button and add following code

if (FileUpload1.HasFile)
            {
                string fileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
                FileUpload1.PostedFile.SaveAs(Server.MapPath("~/Images/") + fileName);
                Response.Redirect(Request.Url.AbsoluteUri);
            }

Step 4 : Index.aspx.cs file

Copy and paste following code on page load event

if (!IsPostBack)
            {
                string[] filePaths = Directory.GetFiles(Server.MapPath("~/Images/"));
                List<ListItem> files = new List<ListItem>();
                foreach (string filePath in filePaths)
                {
                    string fileName = Path.GetFileName(filePath);
                    files.Add(new ListItem(fileName, "~/Images/" + fileName));
                }
                GridView1.DataSource = files;
                GridView1.DataBind();
            }

Step 5: Press F5 and see the result. You can download the demo using following ‘Download Source Code’ button

 

Leave a Comment