Saving Image (Binary Data) to SQL Database and Display in GridView using C# in ASP.Net

Last Reply on Nov 07, 2016 02:01 AM By Andrea

Posted on Nov 07, 2016 02:01 AM

Sir,  Image is saving properly. No issues with the saving. But While displaying an images in GridView would not converting binary to image file.

Below is my code to save data to SQL Database.

 HTML Code:

<table width="100%" border="0">
                   <tr>
                    <td align="right" valign="top" width="30%">Select Event <font color="red">*</font></td>
                    <td width="5%"></td>
                    <td align="left" valign="top" width="65%">
                        <asp:DropDownList ID="DropDownList1" CssClass="textboxNew" runat="server">
                        </asp:DropDownList>
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
                            ControlToValidate="teventname" Display="Dynamic" 
                            ErrorMessage="Select event." InitialValue="0" Font-Size="9pt" SetFocusOnError="True" 
                            ValidationGroup="Photo"></asp:RequiredFieldValidator>
                       </td>
                   </tr>
                   <tr><td height="10" colspan="3"></td></tr>
                   <tr>
                    <td align="right" valign="top" width="30%">Browse Photo <font color="red">*</font></td>
                    <td width="5%"></td>
                    <td align="left" valign="top" width="65%">
                        <asp:FileUpload ID="FileUpload1" runat="server" CssClass="textboxNew" />
                        <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" 
                            ControlToValidate="FileUpload1" Display="Dynamic" 
                            ErrorMessage="Upload Photo" Font-Size="9pt" SetFocusOnError="True" 
                            ValidationGroup="Photo"></asp:RequiredFieldValidator>
                             <asp:RegularExpressionValidator ID="RegularExpressionValidator1" ValidationExpression="([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg)$"
    ControlToValidate="FileUpload1" runat="server" ForeColor="Red" ErrorMessage="Only .jpg OR .jpeg file."
    Display="Dynamic" Font-Size="9pt" ValidationGroup="Photo" />
                       </td>
                   </tr>
                   <tr><td height="10" colspan="3"></td></tr>
                   <tr>
                    <td align="right" valign="top">
                         </td>
                    <td width="5%"></td>
                    <td align="left" valign="top">
                        <asp:Button ID="Button2" runat="server" ValidationGroup="Photo" Text="Submit" 
                            CssClass="btn btn-default" onclick="Button2_Click" />
                        </td>
                   </tr>
                      <tr>
                          <td align="right" valign="top">
                              &nbsp;</td>
                          <td width="5%">
                              &nbsp;</td>
                          <td align="left" valign="top">
                              &nbsp;</td>
                      </tr>
                    <tr><td height="10" colspan="3">
                       
                         
                     </td></tr>
                  </table>

C# Code:

protected void Button2_Click(object sender, EventArgs e)
    {
        
                // Read the file and convert it to Byte Array
                string filePath = FileUpload1.PostedFile.FileName;
                string filename = Path.GetFileName(filePath);
                string exten = Path.GetExtension(filename);
                string contenttype = String.Empty;

                //Set the contenttype based on File Extension
                switch (ext)
                {
                    case ".jpg":
                        contenttype = "image/jpg";
                        break;
                    case ".jpeg":
                        contenttype = "image/jpeg";
                        break;
                }

                if (contenttype != String.Empty)
                {
                    Stream fs = FileUpload1.PostedFile.InputStream;
                    BinaryReader br = new BinaryReader(fs);
                    Byte[] bytes = br.ReadBytes((Int32)fs.Length); 

                    //insert the file into database
                    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["estatesConnectionString"].ConnectionString);
                    SqlCommand cmd = new SqlCommand("insert into PhotoGallery(PhotoFile,ImageType) Values(@PhotoFile,@ImageType)", conn);
                     
                    cmd.Parameters.AddWithValue("@PhotoFile", bytes);
                    cmd.Parameters.AddWithValue("@ImageType", contenttype);
                     
                    conn.Open();
                    int j = cmd.ExecuteNonQuery();
                    conn.Close();

                    if (j > 0)
                    {
                        alert = "Photo saved successfully.";
                        ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "JSCR", "BootstrapDialog.alert('" + alert + "');", true);
                         
                    }
                    else
                    {
                        alert = "Unable to process your request.";
                        ScriptManager.RegisterClientScriptBlock(Page, this.GetType(), "JSCR", "BootstrapDialog.alert('" + alert + "');", true);
                         
                    }
                }
        
    }

==================================================== Display Code For Images:

HTML Code:

 

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
     <center>
          <asp:GridView ID="gvImages" CssClass="Gridview" runat="server" AutoGenerateColumns="False"
HeaderStyle-BackColor="#7779AF" HeaderStyle-ForeColor="white">
<Columns>
 <asp:BoundField DataField="PhotoId" />
   <asp:ImageField DataImageUrlField="PhotoId" DataImageUrlFormatString="ImageCSharp.aspx?ImageID={0}"
                                   ControlStyle-Width = "100" ControlStyle-Height = "100" HeaderText = "Image Thumbnail"/>
                               
                            
</Columns>
</asp:GridView>
     </center>
    </form>
</body>
</html>

  c# Code:

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

public partial class Gallery_Sample : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridData();
        }
    }
    /// <summary>
    /// btnUpload_Click event is used to upload images into database
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
     
    private void BindGridData()
    {
        DataTable dt = new DataTable();

        String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["estatesConnectionString"].ConnectionString;

        string strQuery = "select top 1 * from PhotoGallery";

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

            gvImages.DataSource = dt;

            gvImages.DataBind();

        }

        catch (Exception ex)
        {

            Response.Write(ex.Message);

        }

        finally
        {

            con.Close();

            sda.Dispose();

            con.Dispose();

            dt.Dispose();

        } 
    }
     
    
}

ImageCSharp.aspx (HTML):

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    </div>
    </form>
</body>
</html>

c#:

protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["ImageID"] != null)
        {
            string strQuery = "select PhotoFile from PhotoGallery where PhotoId=@id";

            String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["estatesConnectionString"].ConnectionString;

            SqlCommand cmd = new SqlCommand(strQuery);

            cmd.Parameters.Add("@id", SqlDbType.Int).Value = Convert.ToInt32(Request.QueryString["ImageID"]);

            SqlConnection con = new SqlConnection(strConnString);

            SqlDataAdapter sda = new SqlDataAdapter();

            cmd.CommandType = CommandType.Text;

            cmd.Connection = con;

            DataTable dt = new DataTable();

            try
            {

                con.Open();

                sda.SelectCommand = cmd;

                sda.Fill(dt);

            }

            catch
            {

                dt = null;

            }

            finally
            {

                con.Close();

                sda.Dispose();

                con.Dispose();

            }

            if (dt != null)
            {
                string fname  = System.DateTime.Now.Year.ToString()+System.DateTime.Now.Month.ToString()+System.DateTime.Now.Day.ToString()+
                                System.DateTime.Now.Hour.ToString()+System.DateTime.Now.Minute.ToString()+System.DateTime.Now.Second.ToString()+
                                System.DateTime.Now.Millisecond.ToString();

                Byte[] bytes = (Byte[])dt.Rows[0]["PhotoFile"];

                Response.Buffer = true;

                Response.Charset = "";

                Response.Cache.SetCacheability(HttpCacheability.NoCache);

                Response.ContentType = "image/jpeg";

                Response.AddHeader("content-disposition", "attachment;filename=" + fname);

                Response.BinaryWrite(bytes);

                Response.Flush();

                Response.End();

            }

        }
    }

  Database Script :

USE [GalleryMaster]
GO

/****** Object:  Table [dbo].[PhotoGallery]    Script Date: 11/07/2016 14:26:55 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

SET ANSI_PADDING ON
GO

CREATE TABLE [dbo].[PhotoGallery](
	[PhotoId] [int] IDENTITY(1,1) NOT NULL,
	[PhotoFile] [varbinary](max) NULL,
	[ImageType] [varchar](50) NULL,
 CONSTRAINT [PK_PhotoGallery] PRIMARY KEY CLUSTERED 
(
	[PhotoId] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

 

Posted on Nov 07, 2016 02:01 AM

Hi @Sumeet,
Please try the following

Display images from SQL Server Database in ASP.Net GridView control

It might help you.

Cheers Andrea.