In this article, we will explore how to store images in the database with the help of FileUpload Control and also how to display those images in asp.net GridView Control. For the purpose of this article I have created a table in SQL Server called Images, with three columns, Image Name, Image Type and the Image itself. Now let’s take a look at the form we are going to use, to upload images to this table.
The concept behind this technique is to store the images on disk in a folder that resides in the WebSite root directory while the relative path of the images along with filename is stored in SQL Server database.

Let us start off by first creating a sample database and adding a table that will store the image path. The figure below describes the table structure.
set the ID field to auto increment using the identity property.

Next I’ll add a FileUpload and Button to the aspx page.
<div>
    <asp:FileUpload ID="FileUpload1" runat="server"/>
    <asp:Button ID="btnUpload" runat="server" Text="Upload"
        OnClick="btnUpload_Click" />

</div>

Adding a folder called "images" in my website root directory.
Adding a connection string key to the web.config which will be used to connect to the SQL server Database.
<connectionStrings>
  <add name="conString"

     connectionString="Data Source=.\SQLEXPRESS;database=GridDB;
       Integrated Security=true"/>
</connectionStrings >

Upload and Storing the Image Files. The snippet below gets executed when the upload button is clicked. It gets the uploaded image filename and saves the image in images folder. And then inserts the image file path into the database.protected void btnUpload_Click(object sender, EventArgs e){
    if (FileUpload1.PostedFile != null)

    {

        string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName); 

        //Save files to disk

        FileUpload1.SaveAs(Server.MapPath("images/" +  FileName));

        //Add Entry to DataBase

        String strConnString = System.Configuration.ConfigurationManager

            .ConnectionStrings["conString"].ConnectionString;

        SqlConnection con = new SqlConnection(strConnString);

        string strQuery = "insert into tblFiles (FileName, FilePath)" +

            " values(@FileName, @FilePath)";

        SqlCommand cmd = new SqlCommand(strQuery);

        cmd.Parameters.AddWithValue("@FileName", FileName);

        cmd.Parameters.AddWithValue("@FilePath", "images/" + FileName); 

        cmd.CommandType = CommandType.Text;

        cmd.Connection = con;

        try

        {

            con.Open();

            cmd.ExecuteNonQuery();

        }

        catch (Exception ex)

        {

            Response.Write(ex.Message);

        }

        finally

        {

            con.Close();

            con.Dispose();

        }

    }

}

Display Images. Now the next job is to display the images in GridView control. As you can see the below GridView, I have added 2 Bound Fields which displays ID and File Name and a Image Field which displays the image based on the image path that comes from the database.
<div>
<br />

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false"

       Font-Names = "Arial" >

    <Columns>

       <asp:BoundField DataField = "ID" HeaderText = "ID" />

       <asp:BoundField DataField = "FileName" HeaderText = "Image Name" />

       <asp:ImageField DataImageUrlField="FilePath" ControlStyle-Width="100"

        ControlStyle-Height = "100" HeaderText = "Preview Image"/>

    </Columns>

    </asp:GridView>

</div>

The snippet below is used to display the images in the GridView control. As you will notice I am firing a simple select query and the returned datatable is then bind to the GridView Control.

protected void Page_Load(object sender, EventArgs e)
{

    DataTable dt = new DataTable();

    String strConnString = System.Configuration.ConfigurationManager.

        ConnectionStrings["conString"].ConnectionString;

    string strQuery = "select * from tblFiles order by ID";

    SqlCommand cmd = new SqlCommand(strQuery);

    SqlConnection con =  new SqlConnection(strConnString);

    SqlDataAdapter sda = new SqlDataAdapter();

    cmd.CommandType = CommandType.Text;

    cmd.Connection = con;

    try

    {

        con.Open();

        sda.SelectCommand = cmd;

        sda.Fill(dt);

        GridView1.DataSource = dt;

        GridView1.DataBind(); 

    }

    catch (Exception ex)

    {

        Response.Write(ex.Message);

    }

    finally

    {

        con.Close();

        sda.Dispose();

        con.Dispose();

    }

}

The GridView with images is shown in the figure below.

I hope you will enjoy reading this article you should have learned how to Retrieve images using a file path stored in database in ASP.Net that you can use in your own code. Stay tuned and stay connected for more technical updates with ASPHostPortal.