You must Sign In to post a response.
  • Category: ASP.NET

    Please help me how to store images in database

    My requirement is to storing the images in SQL database, and retriving them. After that i need to show it in the GridView.

    Plz reply as early as possible...
  • #648879
    Hi,

    You may find hundreds of sample code in our resource section. Please check below articles,

    http://www.dotnetspider.com/resources/37955-store-retrieve-image-from-sql-server-using.aspx
    http://www.dotnetspider.com/resources/39304-Storing-reterview-images-form-database.aspx


    Regards,
    Asheej T K

  • #648886
    It is wise to store the image in a folder and save the path/name of the image in the database.

    Create a folder "Images" within your application and use the following code:

    Database Script
    ---------------


    CREATE TABLE TblUsers(
    UserID INT IDENTITY(1,1),
    UserName VARCHAR(30),
    UserPhoto VARCHAR(100))


    Design
    ------


    <div>
    User Name:
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
    User Photo:
    <asp:FileUpload ID="FileUpload1" runat="server" /><br />
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><br />
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <Columns>
    <asp:TemplateField>
    <ItemTemplate>
    <asp:Label ID="Label1" runat="server" Text='<%#Eval("UserName") %>'></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField>
    <ItemTemplate>
    <asp:Image ID="Image1" runat="server" ImageUrl='<%#"~/Images/" + Eval("UserPhoto") %>'
    Height="80px" Width="100px" />
    </ItemTemplate>
    </asp:TemplateField>
    </Columns>
    </asp:GridView>
    <br />
    </div>


    C# Code Behind
    --------------


    protected void Button1_Click(object sender, EventArgs e)
    {
    SqlConnection con = new SqlConnection("server=.;integrated security=true;database=dotnetspider");
    string photo = "";
    string query;
    if (FileUpload1.HasFile)
    {
    FileUpload1.SaveAs(Server.MapPath("~/Images/") + FileUpload1.FileName);
    photo = FileUpload1.FileName;
    }
    else
    {
    photo = "DefaultImage.jpg";
    }
    query = "INSERT INTO TblUsers(UserName, UserPhoto) VALUES('" + TextBox1.Text + "','" + photo + "')";
    SqlCommand com = new SqlCommand(query, con);
    con.Open();
    com.ExecuteNonQuery();
    con.Close();

    bindgrid();
    }

    public void bindgrid()
    {
    SqlConnection con = new SqlConnection("server=.;integrated security=true;database=dotnetspider");
    DataSet ds = new DataSet();
    SqlDataAdapter sqlda = new SqlDataAdapter("select * from TblUsers", con);
    sqlda.Fill(ds, "TblUsers");
    GridView1.DataSource = ds;
    GridView1.DataBind();
    }


    Thanks & Regards
    Paritosh Mohapatra
    Microsoft MVP (ASP.Net/IIS)
    DotNetSpider MVM

  • #648913
    See below code for uploading image in database:

    public partial class CreateProfile : System.Web.UI.Page
    {
    string constring = "Server=dell;Database=Neha;integrated security=true";
    SqlConnection conn = null;
    SqlCommand cmdgetpinfo = null;
    SqlCommand cmdputpinfo = null;
    SqlCommand cmdgetcontactinfo = null;
    SqlCommand cmdputcontactinfo = null;
    SqlCommand cmdgeteduinfo = null;
    SqlCommand cmdputeduinfo = null;
    SqlCommand cmdgetphoto = null;
    SqlCommand cmdputphoto = null;

    SqlParameter p1 = null;
    SqlParameter p2 = null;
    protected void Page_Load(object sender, EventArgs e)
    {
    try
    {
    conn = new SqlConnection(constring);
    conn.Open();
    cmdgetphoto = new SqlCommand("select username from photo where username='" + Session["uname"].ToString() + "'", conn);



    int flag = 0;
    cmdgetphoto.ExecuteNonQuery();
    SqlDataReader dr = cmdgetphoto.ExecuteReader();
    if (dr.HasRows)
    {
    flag = 1;
    }
    dr.Close();

    if (flag == 0)
    {


    string sql4 = "insert into photo(username)values(@username)";
    cmdputphoto = new SqlCommand(sql4, conn);
    cmdputphoto.Parameters.AddWithValue("username", Session["uname"].ToString());
    cmdputphoto.ExecuteNonQuery();

    conn.Close();
    }
    catch (Exception ex)
    {
    Response.Write(ex.Message);
    }


    }

    protected void btnupload_Click(object sender, EventArgs e)
    {
    try
    {
    impupload.SaveAs(Server.MapPath("images\\" + impupload.FileName));

    byte[] imagedata = impupload.FileBytes;

    conn = new SqlConnection(constring);
    conn.Open();

    string query = "update photo set photoname=@OriginalPath,photo=@ImageData where username='" + Session["uname"].ToString() + "'";

    cmdputphoto = new SqlCommand(query, conn);
    cmdputphoto.Parameters.Add(new SqlParameter("@OriginalPath", Session["uname"].ToString()));
    cmdputphoto.Parameters.Add(new SqlParameter("@ImageData",(object)imagedata));
    cmdputphoto.ExecuteNonQuery();
    Label3.Text = "image is successfully uploaded";

    }
    catch (Exception ex)
    {
    Response.Write(ex.Message);
    }
    }
    }

    Regards,
    Sugandha
    Microsoft Certified Technology Specialist
    MY Blog..

  • #648956
    Hi,

    To show the Image in Gridview you need to add "DataGridViewImageColumn" image column in Gridview.

    suppose you get data of image in Bytes then use below code to assign image in gridview:



    DataGridViewImageColumn icol = new DataGridViewImageColumn();

    //suppose data1 is byte array of image

    MemoryStream ms1 = new MemoryStream(data1);

    Image img2 = Image.FromStream(ms1);

    icol.Image = img2;




    hope this will help you

    With Regards
    Kushal

  • #648962
    Hello,
    Please check below code:
    Display Images In GridView From DataBase:


    <%@ WebHandler Language="C#" Class="Handler" %>

    using System;
    using System.Web;
    using System.Configuration;
    using System.Data.SqlClient;

    public class Handler : IHttpHandler {

    public void ProcessRequest (Httpconntext context)
    {
    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = ConfigurationManager.ConnectionStrings
    ["ConnectionString"].ConnectionString;

    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "Select ImageName,Image from Table" +
    " where ID =@NUM";
    cmd.CommandType = System.Data.CommandType.Text;
    cmd.Connection = conn;

    SqlParameter ImgID = new SqlParameter
    ("@NUM", System.Data.SqlDbType.Int);
    ImgID.Value = context.Request.QueryString["ID"];
    cmd.Parameters.Add(ImgID);
    conn.Open();
    SqlDataReader dReader = cmd.ExecuteReader();
    dReader.Read();
    context.Response.BinaryWrite((byte[])dReader["Image"]);
    dReader.Close();
    conn.Close();
    }

    Regards
    Mr.Rajesh
    Software Engg.

  • #649019
    Please check this sample code for the same.


    private void cmdSave_Click(object sender, EventArgs e)
    {
    try
    {
    //Read Image Bytes into a byte array
    byte[] imageData = ReadFile(txtImagePath.Text);

    //Initialize SQL Server Connection
    SqlConnection CN = new SqlConnection(txtConnectionString.Text);

    //Set insert query
    string qry = "insert into ImagesStore (OriginalPath,ImageData) _
    values(@OriginalPath, @ImageData)";

    //Initialize SqlCommand object for insert.
    SqlCommand SqlCom = new SqlCommand(qry, CN);

    //We are passing Original Image Path and
    //Image byte data as sql parameters.
    SqlCom.Parameters.Add(new SqlParameter("@OriginalPath",
    (object)txtImagePath.Text));

    SqlCom.Parameters.Add(new SqlParameter("@ImageData",
    (object)imageData));

    //Open connection and execute insert query.
    CN.Open();
    SqlCom.ExecuteNonQuery();
    CN.Close();

    //Close form and return to list or images.
    this.Close();
    }

    Thanks & Regards
    Anil Kumar Pandey
    Microsoft MVP, DNS MVM


  • This thread is locked for new responses. Please post your comments and questions as a separate thread.
    If required, refer to the URL of this page in your new post.