[Solved] How to insert and retrieve image from database in asp.net using c#

In this article, I will explain with an example, "how to insert and retrieve image from database and in asp.net using c#",for this you have to basic knowledge of insert, delete and update. In this tutorial firstly I am going to make a folder (i.e. UploadedImages) in our project.
After that we will add an asp.net web-form then we have to go for the SQL Server process for creating the procedure. All Right let's get starts.



How to upload image in gridview in asp.net using c#


Step #1:

Create Store Procedure for each operation


create database DBUPLOAD
use DBUPLOAD
create table Employee
(
empid int primary key identity,
name varchar(50),
images varchar(100)
)

create proc sp_fileupload
@name varchar(50),
@images varchar(100)
as
begin
      insert into Employee(name,images)
      values(@name,@images)
end

create proc usp_employee_get
as
begin
select * from EMployee
end


create proc usp_employee_edit
@empid int
as
begin
select * from EMployee where empid=@empid
end


create proc usp_employee_update
@empid int,
@name varchar(50),
@images varchar(100)
as
begin
      update Employee set name=@name,images=@images
      where empid=@empid
end




Step #2:

Add connection string in Web.config file



<configuration>
<connectionStrings>
  <add name="Mycon" providerName="System.Data.SqlClient"   connectionString="initial catalog =DBUPLOAD; data source=SANJAY\SQL2012; integrated security=true"/>
</connectionStrings>
    <system.web>
      <compilation debug="false" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
    </system.web>

</configuration>


Step #3:

Now add one asp.net web form name like upload.aspx  and don't forget to add folder (i.e. UploadedImages)




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

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>Name:</td>
                    <td>
                        <asp:TextBox ID="txt_name" runat="server"></asp:TextBox></td>
                </tr>

                <tr>
                    <td>Select Image</td>
                    <td>
                        <asp:FileUpload runat="server" ID="file_upload" /></td>
                </tr>
                <tr>
                    <td>
                        <td><asp:Button ID="btn_save" runat="server" Text="Save" OnClick="btn_save_Click" /></td>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:GridView ID="grd" runat="server" AutoGenerateColumns="false" OnRowCommand="grd_RowCommand">
                            <Columns>
                                <asp:TemplateField HeaderText="Employee Name">
                                    <ItemTemplate>
                                        <%#Eval("name") %>
                                    </ItemTemplate>
                                </asp:TemplateField>

                                <asp:TemplateField HeaderText="Employee Image">
                                    <ItemTemplate>
                                        <asp:Image ID="img" runat="server" Width="50px" Height="40px" ImageUrl='<%#Eval("images","~/UploadedImages/{0}") %>' />
                                    </ItemTemplate>
                                </asp:TemplateField>

                                 <asp:TemplateField>
                                    <ItemTemplate>
                                       <asp:LinkButton ID="btnedit" runat="server" Text="Edit" CommandName="EDT" CommandArgument='<%#Eval("empid") %>'></asp:LinkButton>
                                    </ItemTemplate>
                                </asp:TemplateField>
                            </Columns>
                        </asp:GridView>
                    </td>
                </tr>
                <tr>
                    <td>
                        <asp:Label ID="lblmsg" runat="server"></asp:Label>
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>

</html>


Step #4:

Now the last step, don't forget to add necessary namspace


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.Data;
using System.Configuration;
using System.IO;    //Important NameSpace

public partial class upload : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Mycon"].ConnectionString);
    SqlCommand cmd;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Display();
        }
    }
    public void Display()
    {
        con.Open();
        SqlCommand cmd = new SqlCommand("usp_employee_get", con);
        cmd.CommandType = CommandType.StoredProcedure;
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        da.Fill(ds);
        con.Close();
        if (ds.Tables[0].Rows.Count > 0)
        {
            grd.DataSource = ds;
            grd.DataBind();
        }
        else
        {
            grd.DataSource = null;
            grd.DataBind();
        }
    }
    protected void btn_save_Click(object sender, EventArgs e)
    {
        string FN = "";
        string Ext = "";

        if (btn_save.Text == "Save")
        {
            FN = DateTime.Now.Ticks.ToString() + Path.GetFileName(file_upload.PostedFile.FileName);
            Ext = Path.GetExtension(file_upload.PostedFile.FileName);
            if (Ext == ".jpg" || Ext == ".jpeg" || Ext == ".png")
            {
                lblmsg.Text = "";
                file_upload.SaveAs(Server.MapPath("UploadedImages" + "\\" + FN));
                con.Open();
                SqlCommand cmd = new SqlCommand("sp_fileupload", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@name", txt_name.Text);
                cmd.Parameters.AddWithValue("@images", FN);
                cmd.ExecuteNonQuery();
                con.Close();
                Display();
            }
            else
            {
                lblmsg.Text = "please upload only .jpg or .jpeg or .png files !!!";
            }
        }
        else
        {
            FN = Path.GetFileName(file_upload.PostedFile.FileName);
            Ext = Path.GetExtension(file_upload.PostedFile.FileName);

            lblmsg.Text = "";

            con.Open();
            SqlCommand cmd = new SqlCommand("usp_employee_update", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@empid", ViewState["EID"]);
            cmd.Parameters.AddWithValue("@name", txt_name.Text);
            if (FN != "")
            {
                cmd.Parameters.AddWithValue("@images", FN);
                file_upload.SaveAs(Server.MapPath("UploadedImages" + "\\" + FN));
                File.Delete(Server.MapPath("UploadedImages" + "\\" + ViewState["IMG"]));
            }
            else
            {
                cmd.Parameters.AddWithValue("@images", ViewState["IMG"]);
            }
            cmd.ExecuteNonQuery();
            con.Close();
            Display();
        }
    }
    protected void grd_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "EDT")
        {
            con.Open();
            SqlCommand cmd = new SqlCommand("usp_employee_edit", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@empid", e.CommandArgument);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            con.Close();
            if (ds.Tables[0].Rows.Count > 0)
            {
                txt_name.Text = ds.Tables[0].Rows[0]["name"].ToString();
                ViewState["IMG"] = ds.Tables[0].Rows[0]["images"].ToString();
                btn_save.Text = "Update";
                ViewState["EID"] = e.CommandArgument;
            }
        }
    }
}


Note: Some time the image upload very well but not in grid-view, in this case, you may put debugger on your web-form and do find step by step process. So that you can easily find the error



Read More-Know More



Previous
Next Post »