Save and Retrieve Images from Database and Display in Gridview


asp.net save and retrieve image from database and display in gridview

In my Previous Articles i shown you how to save and retrieve image from database
In this articles i'm going to explain how to Save and Retrieve Image From Database and display in Gridview container in Asp.net by using C# Coding. In above image you see i have used 5 controllers i.e 2 textbox, 1 fileuploader and 1 button control, Gridview

  1. TextBox is used to display ImageID is nothing but a Auto Generate Number,
  2. TextBox is used to enter Image Name
  3. Fileuploader control is used to choose Image from your device
  4. GridView control is used to display image data from database

Create Image Database

save image and retrieve image from database in asp.net

Create CSS Code


 <style type="text/css">
     #tableimg
     {
         border-collapse:collapse;
         width:600px;         
     }
     #tableimg th
     {
         padding:5px 10px 5px 10px;
         background-color:#222;
         color:#fff;
         border:1px solid #222;
     }
     .row1
     {
         border:1px solid #222;
         padding:3px;
         width:250px;
         text-align:left;
     }
     .row2
     {
         border:1px solid #222;
         padding:3px;
         width:350px;
         text-align:left;
     }
     .txt
     {
         padding:5px;
         width:300px;
     }
     .ImageBox
     {
         width:150px;
         height:150px;
         padding:5px;
         margin:5px;
         border:1px solid #e4e4e4;
     }
     .ImageBox:hover
     {
         width:150px;
         height:150px;
         padding:5px;
         margin:5px;
         border:1px solid #e4e4e4;
         background-color:#222;
     }
   </style>

Create HTML Page


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
   <style>
   
    ---------- CSS Code Here----------
    
   </style>
</head>
<body>
    <form id="form1" runat="server">
    <div style="margin:30px 40px 0px 20px;">
      <table id="tableimg">
       <tr>
        <th colspan="2">Save and Retrieve Image from Database</th>
       </tr>
       <tr>
        <td class="row1">
         Enter Image ID :
        </td>
        <td class="row2">
         <asp:TextBox ID="txtimageID" runat="server" CssClass="txt" BackColor="Silver" 
                ReadOnly="True"></asp:TextBox>
        </td>
       </tr>
       <tr>
        <td class="row1">
         Enter Image Name :
        </td>
        <td class="row2">
         <asp:TextBox ID="txtimagename" runat="server" CssClass="txt"></asp:TextBox>
        </td>
       </tr>
       <tr>
        <td class="row1">
         Choose Image :
        </td>
        <td class="row2">
         <asp:FileUpload ID="FileUpload1" runat="server" CssClass="txt" />
        </td>
       </tr>
       <tr>
        <td colspan="2">
         <asp:Button ID="btn_saveimage" runat="server" Text="Image Save" 
                onclick="btn_saveimage_Click" />
        </td>
       </tr>
       </table>
    </div>
    <br />
 <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" 
        BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" 
        CellPadding="4">
        <Columns>
            <asp:TemplateField HeaderText="Image ID">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bindundefined"imgid") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%# Bindundefined"imgid") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Image Name">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bindundefined"imagename") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="Label2" runat="server" Text='<%# Bindundefined"imagename") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Display Image">
                <EditItemTemplate>
                    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Image ID="Image1" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
        <HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
        <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
        <RowStyle BackColor="White" ForeColor="#003399" />
        <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
        <SortedAscendingCellStyle BackColor="#EDF6F6" />
        <SortedAscendingHeaderStyle BackColor="#0D4AC4" />
        <SortedDescendingCellStyle BackColor="#D6DFDF" />
        <SortedDescendingHeaderStyle BackColor="#002876" />
    </asp:GridView>
    </form>
</body>
</html>

C# Coding : Namespace


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

C# Coding : Image Auto Generate ID


GetImageID method is used to execute SQL Query i.e Select ISNULL(MAX(imgid),10000) from image this select query means whenever we execute this query its retrieve MAX(imgid) value from imgid column, if imgid column is null then it will return Null values instead of null values we can assign some value. ISNULL(MAX(imgid),10000) is used to return 10000 if imgid column is NULL.


private int GetImageID()
    {
        try
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("select Isnull(MAX(imgid),10000) from image", con);
            int i = Convert.ToInt32(cmd.ExecuteScalar());
            i++;
            return i;
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
        }
    }

C# Coding : Display Image's

DisplayImage() method is used to retrieve all images data from Database and display in gridview control.

private void DisplayImage()
    {
       SqlDataAdapter da = new SqlDataAdapter("Select * from Image", con);
        DataSet ds=new DataSet();
        da.Fill(ds);
        if(ds.Tables[0].Rows.Count>0)
        {
           GridView1.DataSource = ds.Tables[0];
           GridView1.DataBind();                

           for (int j = 0; j < GridView1.Rows.Count; j++)
            {
              byte[] bytes = (byte[])ds.Tables[0].Rows[j]["image"];
              string strbase64 = Convert.ToBase64String(bytes); 
                       
              Image img = (Image)GridView1.Rows[j].FindControl("Image1");
              img.CssClass = "ImageBox";
              img.ImageUrl = "data:Image/png;base64," + strbase64;
            }
        }
    }

C# Coding : Page Loading

In Page Load DisplayImage() method is used to retrieve all images and display in dynamically created image control. GetImageID() method is return integer value which is nothing but a ImageID and we are assigning that value to TextBox Image Id (txtimageID).


 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DisplayImage();
            int ImgID = GetImageID();
            txtimageID.Text = ImgID.ToString();
        }
    }

C# Coding : Image Save Button Click


  protected void btn_saveimage_Click(object sender, EventArgs e)
    {
        try
        {            
            HttpPostedFile postfile = FileUpload1.PostedFile;
            string filename = Path.GetFileName(postfile.FileName);
            string fileExtension = Path.GetExtension(filename);
            int filesize = postfile.ContentLength;
            if (fileExtension.ToLower() == ".jpg" || fileExtension.ToLower() == ".png" || fileExtension.ToLower() == ".gif" || fileExtension.ToLower() == ".bmp")
            {
                Stream imgstream = postfile.InputStream;
                BinaryReader binaryreader = new BinaryReader(imgstream);
                byte[] imgbytes = binaryreader.ReadBytes((int)imgstream.Length);

                //Save Image Data into Database
                con.Open();
                SqlCommand cmd = new SqlCommand("Insert into Image(imgid, imagename, image) values('" + txtimageID.Text + "','" + txtimagename.Text + "',@image)", con);
                cmd.Parameters.AddWithValue("@image", SqlDbType.Binary).Value = imgbytes;
                int i=cmd.ExecuteNonQuery();
                con.Close();
                if (i > 0)
                {
                    DisplayImage();
                    int ImgID = GetImageID();
                    txtimageID.Text = ImgID.ToString();                    
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
        }

    }
Tag : ASP.NET, Image
5 Komentar untuk "Save and Retrieve Images from Database and Display in Gridview"

Thanks for sharing the information, please share some filter option in data gridview.

http://allittechnologies.blogspot.com/2016/02/gridview-filter-through-dropdownlists-in-aspnet-by-using-csharp-coding.html

Excellent post!!! The future of .net application development is on positive note. It offers huge career prospects for talented professionals all over the world. Training on .net technology will ensure good salary package. DOT NET Training in Chennai | .NET Training in Chennai

Hi
I am working on project video tutorial so can i use the same method for videos
Pls reply its urgent

Back To Top