Home > ASP.Net > Display Images in GridView Control using the path stored in SQL Server database

Display Images in GridView Control using the path stored in SQL Server database


Hi

In this post i will provide an example to Display Images in GridView Control using the path stored in SQL Server database

step1 :- Open SQL Server and create database and add new table called “tblPic” which has the following fields :-

* Id -> PK, Int , Identity

* Title -> nvarchar(20)

* Picture -> nvarchar(20)

step2 : create website and add new folder and name it images where i will upload image in it

step 3 : add new Web.Config file and in it add the connection string

<connectionStrings>
  <add name="conString"
     connectionString="Data Source=.\SQLEXPRESS;database=Database;
       Integrated Security=true"/>
</connectionStrings >

step4 : add new web page and add TextBox , FileUpload , Gridview and Button

<asp:FileUpload ID="FileUpload1" runat="server"/>
<asp:TextBox ID="txt_Title" runat="server" BorderColor="#99CC66" BorderStyle="Dashed"></asp:TextBox>
    <asp:Button ID="btnUpload" runat="server" Text="Upload"
        OnClick="btnUpload_Click" />

<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:TemplateField HeaderText="Image"">
       <ItemTemplate>

  <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("Picture", "~/images/{0}") %>'/>
       </ItemTemplate>
     </asp:TemplateField>
    </Columns>

</asp:GridView>

step 5 : In Button Click add the following code to save image name in database and upload it in images folder

protected void btnUpload_Click(object sender, EventArgs e)
{
    if (FileUpload1.PostedFile != null)
    {
        string FileName = Guid.NewGuid().ToString() + Path.GetExtension(FileUpload1.FileName); 
        //The above code is to rename File Name to avoid douplicated name
        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 tblPic (Title, Picture)" + " values(@Title, @Picture)";

        SqlCommand cmd = new SqlCommand(strQuery);
        cmd.Parameters.AddWithValue("@Title", txt_Title.Text);
        cmd.Parameters.AddWithValue("@Picture",  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();
        }
    }
}

step 6 : To Display Image in Gridview add this code in Page_Load

protected void Page_Load(object sender, EventArgs e)
{
    DataTable dt = new DataTable();
    String strConnString = System.Configuration.ConfigurationManager.
        ConnectionStrings["conString"].ConnectionString;
    string strQuery = "select * from tblPic 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();
    }
}

Hope this helps

Good Luck

Advertisements
Categories: ASP.Net

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: