ASP.NET: Save and Retrieve Images from Database to GridView Using C#

Introduction:

In previous articles, we delved into the intricacies of saving and retrieving images from databases. Now, let's elevate our understanding and explore the seamless integration of these processes in ASP.NET, employing the power of C# coding. The tutorial guides you through creating a robust image database, crafting essential CSS for a visually appealing layout, and implementing HTML and C# code to make it all come to life.

asp.net save and retrieve image from database and display in 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

To kick things off, let's set up a database for our images. This ensures a structured approach to storing and retrieving image data. Check out the image below for a glimpse into the database schema.

save image and retrieve image from database in asp.net

Stylish CSS for a Captivating Layout

A visually appealing layout enhances the user experience. Dive into the CSS code provided to create an aesthetically pleasing design. From defining table styles to specifying image box characteristics, every detail contributes to an engaging interface.


 <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>

HTML Page Design for User Interaction

The heart of any web application is its user interface. Craft an HTML page with ASP.NET controls such as TextBoxes, FileUpload, and GridView. These controls form the canvas where users interact with the image-saving mechanism.


<%@ 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: Making It All Work

Image Auto Generate ID

A critical aspect of image management is the unique identification of each image. The GetImageID method ensures the automatic generation of Image IDs, making them ready for storage.


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;

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

Displaying Images Dynamically

The DisplayImage method retrieves image data from the database and dynamically populates the GridView with images. Each image is converted into base64 format for seamless display.


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;
            }
        }
    }


Page Loading

In the Page_Load event, images are displayed using the DisplayImage method, and the Image ID is auto-generated using GetImageID. This ensures that users are greeted with a comprehensive view of available images.


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

Image Save Button Click

When users upload an image, the btn_saveimage_Click event is triggered. This event handles the image file, saves it to the database, and refreshes the GridView to reflect the updated image list.


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

    }

Conclusion:

Mastering image management in ASP.NET involves orchestrating a symphony of database interactions, HTML design, CSS styling, and C# coding. This tutorial provides a comprehensive guide to seamlessly save and retrieve images, creating a visually appealing and functional web application. Dive in, explore, and elevate your ASP.NET skills!

Post a Comment

4 Comments

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

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

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

    ReplyDelete