ASPSnippets

Alerts
Get notified when a new article is published.

Name
 
Email

Your email will always be private and will not be shared.

Follow us on twitter.
 
Display Images in GridView Control using the path stored in SQL Server database
Author Name: Mudassar Khan Published Date: April 20, 2009
Filed Under :
ASP.Net
 |
SQL Server
 |
GridView
Views: 8391

In this article, I am explaining how to store images and pictures on disk and their path in the database with the help of FileUpload Control and also how to display those images in asp.net GridView Control.

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.

First we will start with creating database table that will store the image path. The figure below describes the table structure



Table Structure

As you can see above I have 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>

 

Then I am adding a folder called images in my website root directory. Refer figure below.



Adding images folder to store images

Connection String

And then I am 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.

       

 

C#

 

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();

        }

    }

}

 

      

 

VB.Net

Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)

  If FileUpload1.PostedFile IsNot Nothing Then

   Dim FileName As String = Path.GetFileName(FileUpload1.PostedFile.FileName)

 

   'Save files to disk

   FileUpload1.SaveAs(Server.MapPath("images/" & FileName))

 

   'Add Entry to DataBase

   Dim strConnString As [String] = System.Configuration. _

    ConfigurationManager.ConnectionStrings("conString"). _

    ConnectionString

   Dim con As New SqlConnection(strConnString)

   Dim strQuery As String = "insert into tblFiles (FileName, FilePath)" _

    & " values(@FileName, @FilePath)"

   Dim cmd As 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 ex As Exception

     Response.Write(ex.Message)

   Finally

     con.Close()

     con.Dispose()

   End Try

  End If

End Sub

 

The figure below displays how the data is stored in the database table.



Data Stored in table

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.

C#

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();

    }

}

 

  VB.Net

 

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load

        Dim dt As New DataTable()

        Dim strConnString As [String] = System.Configuration. _

        ConfigurationManager.ConnectionStrings("conString")_

        .ConnectionString()

        Dim strQuery As String = "select * from tblFiles order by ID"

        Dim cmd As New SqlCommand(strQuery)

        Dim con As New SqlConnection(strConnString)

        Dim sda As New SqlDataAdapter()

        cmd.CommandType = CommandType.Text

        cmd.Connection = con

        Try

            con.Open()

            sda.SelectCommand = cmd

            sda.Fill(dt)

            GridView1.DataSource = dt

            GridView1.DataBind()

        Catch ex As Exception

            Response.Write(ex.Message)

        Finally

            con.Close()

            sda.Dispose()

            con.Dispose()

        End Try

End Sub

 

The GridView with images is shown in the figure below



Images displayed using GridView control

You can download the source in VB.net and C# using the link below.

GridViewImagesOnDisk.zip (1.01 mb)

If you like this article, help us grow by bookmarking this page on any social bookmarking site.
Bookmark and Share Page copy protected against web site content infringement by Copyscape

Related Articles

Comments

HBK said:
Great yar thanks.. Nice Article..
February 08, 2010  

balu said:
nice articlegreat work
February 27, 2010  

Teo said:
Hello nice article but i cant make it work i get :br BC30451: Name FileUpload1 is not declared.br br Any help will be much appreciated br br thank you
April 27, 2010  

Mudassar Khan said:
Reply To: Teo
Make sure you added a FileUpload Control with the ID FileUpload1
April 29, 2010  

preet said:
Very very nice article. It helps me a lot.Great work.br Thanks a lot.
May 05, 2010  

YM said:
Thanks for the great articlebr In my case I have two projects in the same solution. Is there any way of accessing the images folder saved in solution 1
May 22, 2010  

Andre said:
Very well done. Thanks for including the C# as well as the VB code.
May 22, 2010  

Mudassar Khan said:
Reply To: YM
Refer here
http://www.aspsnippets.com/Articles/Displaying-images-that-are-stored-outside-the-Website-Root-Folder.aspx
May 25, 2010  

obaid said:
tanks alot for this website and this articel
June 16, 2010  

Maneesh Deepankar said:
Thanks a lot of Very Good
June 24, 2010  

Add Comments

You can add your comment about this article using the form below. Make sure you provide a valid email address
else you won't be notified when the author replies to your comment

Please note that all comments are moderated and will be deleted if they are
  • Not relavant to the article
  • Spam
  • Advertising campaigns or links to other sites
  • Abusive content.
There is no need to add BR tags. Simply press enter for new line

Name*  
Email*
Comment*  
Security code
Security code