Coding of Save Image in SQL Database and fetch from database in ASP.NET

Unique Coding of Save Image In SQL Database and Fetch from Database in Image Box.

Save Image in SQL databas and retrieve from Databas in Asp.Net. Save Image in Database

Hello, Friend Here I am going to tell you a nice coding of Save Image in SQL Database and fetch it from Database with Giving Unique Id. It is very-very Important Coding these days because we need anywhere to save the Image and fetch from when we need. So It is Important that you have to write a Unique code for it. Occasionally we search the code of net and we did not understand well how to run the program. because it is too much longer and not in step- by step instruction so that we became unable to run this. In the view of this all Problem, I describe Step- by - Step Instruction.

Note: Take care of only table name, Column Name, And database Name, because it is very important here. Here I describe our own created coding which is run successfully, so I think you also run this program, You can change Table Name, Column Name, Database name as your Computer  Program.
Let's see how is it possible



First of All  Design the  page as required here I took two labels and two textboxes two buttons and one image box and one Leupold control on the page
.
Step 1:-

First of all, create a table as in SQL 2005/ 2008 . as you see in my database name and table name
you can change the database name and table name but you should take care of this.

Create database Hollywood
Use it
 Create a table
(
Roll varchar(50),
Name varchar(50),
Image  varbinary(max)
)

Run it
 Note:  the format of Image should be above otherwise many be not run.

Step 2:-

Now double click on the form  and write the following namespace

using System.Data.SqlClient;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;

 Step 3:-

And  write the code below  public partial class

SqlConnection sc = new SqlConnection("Data Source = .; Initial Catalog = Hollybood; Integrated Security = true;");


Note: Hollywood is database name.

Step 4:-

Now write the code below page load event as-



FileUpload1.Attributes.Add("onpropertychange", "show");
Now go to the page and dubble click on the save button and write the following code as follow:-
FileUpload1.SaveAs(Server.MapPath("~\\pict1.jpg"));
        FileStream fs = new FileStream(Server.MapPath("~\\pict1.jpg"), FileMode.Open);
        Byte[] date = new byte[fs.Length];
        fs.Read(date, 0, (int)fs.Length);
        fs.Close();
        SqlCommand cmd = new SqlCommand("insert into janu(Roll, Name, image)values(@Roll,@Name,@image)", sc);
        cmd.Parameters.AddWithValue("@Roll", TextBox1.Text);
        cmd.Parameters.AddWithValue("@Name", TextBox2.Text);
        SqlParameter pict = new SqlParameter("@image", SqlDbType.VarBinary);
        pict.Value = date;
        cmd.Parameters.Add(pict);
        sc.Open();
        cmd.ExecuteNonQuery();
        // con.Close();
        sc.Close();
        Response.Write(" image succeful saved");
        Image1.ImageUrl = null;


Note: take care here the column name as you mention in the database as same like write here it may be case sensitive.

 Step 5:-
Important Instruction 
 To create a map Path
(Note;) create a Map Path here as like
Go to view menu and open solution explorer
right click on the path above shown on the solution explorer  as see you in your upper right corner in Solution explorer like this, right click and create a folder(E:\ AmitProgram\Amit)
Create a folder as require Here pict1
It is necessary other wise program does not run.

Step 6:-
Now double click on display button and write the following code as follow

SqlCommand cmd = new SqlCommand("select *from janu where roll='" + TextBox1.Text + "'", sc);
       
        sc.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.HasRows == true)
        {
            dr.Read();
            TextBox2.Text = dr["name"].ToString();
            byte[] data = (byte[])dr["image"];
            MemoryStream str = new MemoryStream();
            str.Write(data, 0, data.Length);
            Bitmap img = new Bitmap(str);
            img.Save(Server.MapPath("~\\pict1.jpg"));
            Image1.ImageUrl = "pict1.jpg";
            //con.Close();
            sc.Close();
        }
        else
        {
            Image1.ImageUrl = null;
            TextBox2.Text = "";
        }

Note:-  Janu is the name of the table

 Step 7:-

Now there is very important coding
 Come on the page and go to the source page and write the following code below the title tag

<script type = "text/javascript">
    funcion show()
    {
    document.getElementById("Image1").sec = document.getElementById("FileUpLoad1").value;
    }
    </script>


Note: map path is necessary so you must create it as I above direction’
Now speak the Jai maa and run the program.



Best of luck for nice coding. You can save and retrieve by Giving the Id.




Now I want to give to direct All Coding of it Nice and Important program, If you are able to edit this you can change the code as in your system database  and run this program


Save Image In database IN C# Coding

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Data.SqlClient;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
public partial class _Default : System.Web.UI.Page
{
    SqlConnection sc = new SqlConnection("Data Source = .; Initial Catalog = Hollybood; Integrated Security = true;");
    protected void Page_Load(object sender, EventArgs e)
    {
        FileUpload1.Attributes.Add("onpropertychange", "show");
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        FileUpload1.SaveAs(Server.MapPath("~\\pict1.jpg"));
        FileStream fs = new FileStream(Server.MapPath("~\\pict1.jpg"), FileMode.Open);
        Byte[] date = new byte[fs.Length];
        fs.Read(date, 0, (int)fs.Length);
        fs.Close();
        SqlCommand cmd = new SqlCommand("insert into janu(Roll, Name, image)values(@Roll,@Name,@image)", sc);
        cmd.Parameters.AddWithValue("@Roll", TextBox1.Text);
        cmd.Parameters.AddWithValue("@Name", TextBox2.Text);
        SqlParameter pict = new SqlParameter("@image", SqlDbType.VarBinary);
        pict.Value = date;
        cmd.Parameters.Add(pict);
        //con.Open();
        sc.Open();
        cmd.ExecuteNonQuery();
        // con.Close();
        sc.Close();
        Response.Write(" image succeful saved");
        Image1.ImageUrl = null;
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("select *from janu where roll='" + TextBox1.Text + "'", sc);
       
        sc.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.HasRows == true)
        {
            dr.Read();
            TextBox2.Text = dr["name"].ToString();
            byte[] data = (byte[])dr["image"];
            MemoryStream str = new MemoryStream();
            str.Write(data, 0, data.Length);
            Bitmap img = new Bitmap(str);
            img.Save(Server.MapPath("~\\pict1.jpg"));
            Image1.ImageUrl = "pict1.jpg";
            //con.Close();
            sc.Close();
        }
        else
        {
            Image1.ImageUrl = null;
            TextBox2.Text = "";
        }
    }
}



 Now I want to give you All Coding of it in HTML (As source code)


<%@ 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>Untitled Page</title>
    <script type = "text/javascript">
    funcion show()
    {
    document.getElementById("Image1").sec = document.getElementById("FileUpLoad1").value;
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Style="left: 28px; position: relative; top: 49px"
            Text="Roll"></asp:Label>
        <asp:Label ID="Label2" runat="server" Style="left: -6px; position: relative; top: 119px"
            Text="Name"></asp:Label>
        <asp:TextBox ID="TextBox1" runat="server" Style="left: 35px; position: relative;
            top: 44px"></asp:TextBox>
        <asp:TextBox ID="TextBox2" runat="server" Style="left: -123px; position: relative;
            top: 121px"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Style="left: -303px;
            position: relative; top: 231px" Text="save" />
        <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Style="left: -162px;
            position: relative; top: 230px" Text="Display" />
        <asp:Image ID="Image1" runat="server" Height="223px" Style="left: -27px; position: relative;
            top: 230px" Width="197px" /><br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        <asp:FileUpload ID="FileUpload1" runat="server" Style="left: 422px; position: relative;
            top: -28px" /><br />
        <br />
        <br />
   
    </div>
    </form>
</body>
</html>