I want to insert the image into database & Retrive the data back & display into DataGridView..


Foll is the code the inserts the image data into Databse--

protected void Button1_Click(object sender, EventArgs e)
    {

        if (FileUpload1.PostedFile.FileName == null
|| FileUpload1.PostedFile.FileName == "")
        {
            lblErrors.Text = "Please Select the file";
                  }
        else
        {
         byte[] myimage = new byte[FileUpload1.PostedFile.ContentLength]; 
HttpPostedFile Image = FileUpload1.PostedFile; 
Image.InputStream.Read(myimage, 0, (int)FileUpload1.PostedFile.ContentLength);

query = "Insert into ImageGallery1 values(@Image_Content)";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("@Image_Content", myimage);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();

        }
           }

I drag the Grdview onto the second form--

SOURCE TAB

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:TemplateField HeaderText="Template">
                <itemtemplate>
                 <asp:Image ID="Image1" runat="server"  /> 
                </itemtemplate>
                </asp:TemplateField>
                                </Columns>
        </asp:GridView>

Foll code raed the binary data from the database,but mine code is displaying image on page load-

public partial class Default2 : System.Web.UI.Page
{
    string query;
    SqlConnection conn = new SqlConnection("Data Source=SONIA-B408A4159\\SQLEXPRESS;Initial catalog=sonia;Integrated Security=true");
    SqlDataReader dr;
    SqlCommand cmd;

    protected void Page_Load(object sender, EventArgs e)
    {
        query = "select * from ImageGallery1";
        conn.Open();
        cmd=new SqlCommand (query ,conn );
        dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            int contentlength = Convert .ToInt32 (dr.GetBytes(0, 0, null, 0, int.MaxValue));
            byte[] buffer = new byte[contentlength];
            dr.GetBytes(0, 0, buffer, 0, contentlength);
            Response.BinaryWrite(buffer); 

        }


    }
}

I do not know how to insert image into Gridview,Can somebody tell me how to do that??//

I want to insert the image into database & Retrive the data back & display into DataGridView..


Foll is the code the inserts the image data into Databse--

protected void Button1_Click(object sender, EventArgs e)
    {

        if (FileUpload1.PostedFile.FileName == null
|| FileUpload1.PostedFile.FileName == "")
        {
            lblErrors.Text = "Please Select the file";
                  }
        else
        {
         byte[] myimage = new byte[FileUpload1.PostedFile.ContentLength]; 
HttpPostedFile Image = FileUpload1.PostedFile; 
Image.InputStream.Read(myimage, 0, (int)FileUpload1.PostedFile.ContentLength);

query = "Insert into ImageGallery1 values(@Image_Content)";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("@Image_Content", myimage);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();

        }
           }

I drag the Grdview onto the second form--

SOURCE TAB

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:TemplateField HeaderText="Template">
                <itemtemplate>
                 <asp:Image ID="Image1" runat="server"  /> 
                </itemtemplate>
                </asp:TemplateField>
                                </Columns>
        </asp:GridView>

Foll code raed the binary data from the database,but mine code is displaying image on page load-

public partial class Default2 : System.Web.UI.Page
{
    string query;
    SqlConnection conn = new SqlConnection("Data Source=SONIA-B408A4159\\SQLEXPRESS;Initial catalog=sonia;Integrated Security=true");
    SqlDataReader dr;
    SqlCommand cmd;

    protected void Page_Load(object sender, EventArgs e)
    {
        query = "select * from ImageGallery1";
        conn.Open();
        cmd=new SqlCommand (query ,conn );
        dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            int contentlength = Convert .ToInt32 (dr.GetBytes(0, 0, null, 0, int.MaxValue));
            byte[] buffer = new byte[contentlength];
            dr.GetBytes(0, 0, buffer, 0, contentlength);
            Response.BinaryWrite(buffer); 

        }


    }
}

I do not know how to insert image into Gridview,Can somebody tell me how to do that??//

check this
http://www.aspdotnetcodes.com/Insert_Images_Database.aspx

Hi

It's quite simple since image is stored in database you cannot just give its URL to tag img or ImageField in grid, you need to create a handler which will read the image from database and send you the image in response. I am pasting a code sample which should help you understand this better.

Handler:create a file with this name on webserver
GetDBImage.ashx
<%@ WebHandler Language="C#" Class="GetDBImage" %>

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

public class GetDBImage : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        context.Response.Clear();
        context.Response.ContentType = "image/jpg";
        if (context.Request.QueryString["Id"] != null)
        {
            using (SqlConnection conn = new SqlConnection("Data Source=EIL-SW-DSK-063;Initial Catalog=Test_eMinerva4_6;User ID=sa; password=sqlpassword76"))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = "Select StudentPhoto from Student Where StudentNo = @StudentNumber";
                    cmd.Parameters.AddWithValue("@StudentNumber", int.Parse(context.Request.QueryString["Id"]));
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = conn;
                    conn.Open();
                    SqlDataReader dr = cmd.ExecuteReader();

                    if (dr.Read()) 
                    {
                        context.Response.BinaryWrite((byte[])dr["StudentPhoto"]);
                    }
                }
            }
        }
        else 
        {
            //send blank image
            context.Response.WriteFile(@"/Testweb/images/blank.jpeg");
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

======================
aspx file

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

<!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>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label ID="lblMessage" runat="server"></asp:Label><br />
            <br />
            <asp:GridView ID="GVStudentList" runat="server" AllowPaging="True" AllowSorting="True"
                AutoGenerateSelectButton="True" BackColor="White" OnSelectedIndexChanging="GVStudentList_SelectedIndexChanging"
                OnPageIndexChanging="GVStudentList_PageIndexChanging" OnSorting="GVStudentList_Sorting">
                <SelectedRowStyle BackColor="#FF80FF" ForeColor="#404040" />
                <HeaderStyle BackColor="#C0C0FF" BorderColor="DodgerBlue" ForeColor="SaddleBrown" />
                <AlternatingRowStyle BackColor="#E0E0E0" BorderColor="Silver" ForeColor="#404040"
                    HorizontalAlign="Left" VerticalAlign="Top" />
                <Columns>
                    <asp:ImageField DataImageUrlField="StudentNo" DataImageUrlFormatString="~/GetDbImage.ashx?Id={0}" />
                </Columns>
            </asp:GridView>
            <br />
            <table>
                <tr>
                    <td colspan="3">
                        Upload image for :<asp:Label ID="lblSelectedStudentNumber" runat="server"></asp:Label>
                        &gt;&gt;
                        <asp:Label ID="lblSelectedStudentName" runat="server"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td>
                        Upload Image</td>
                    <td>
                    </td>
                    <td style="width: 736px">
                        <asp:FileUpload ID="fpStudentPhoto" runat="server" Width="717px" /></td>
                </tr>
                <tr>
                    <td style="height: 26px">
                    </td>
                    <td style="height: 26px">
                    </td>
                    <td style="width: 736px; height: 26px">
                        <asp:Button ID="btnSubmit" runat="server" Text="Save Image" OnClick="btnSubmit_Click" /></td>
                </tr>
            </table>
            <br />
            <br />
        </div>
    </form>
</body>
</html>

=====================
.cs file
using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;

public partial class SaveImageToDB : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            GVStudentList.Attributes.Add("LastSortByExpression".ToLower(), "");
            GVStudentList.Attributes.Add("LastSortByDirection".ToLower(), "");
            GVStudentList.DataSource = DataSource.GetData().Tables[0];
            GVStudentList.DataBind();
        }

    }

    protected void GVStudentList_Sorting(object sender, GridViewSortEventArgs e)
    {
        DataSet ds = DataSource.GetData();
        DataView dv;
        e.SortDirection = (GVStudentList.Attributes["LastSortByExpression"].ToLower() == e.SortExpression.ToLower()) ? ((GVStudentList.Attributes["LastSortByOrder"] == SortDirection.Ascending.ToString()) ? SortDirection.Descending : SortDirection.Ascending) : SortDirection.Ascending;
        if (e.SortDirection == SortDirection.Ascending)
            dv = new DataView(ds.Tables[0], "1=1", string.Format("{0} {1}", e.SortExpression, "Asc"), DataViewRowState.CurrentRows);
        else
            dv = new DataView(ds.Tables[0], "1=1", string.Format("{0} {1}", e.SortExpression, "Desc"), DataViewRowState.CurrentRows);

        GVStudentList.Attributes["LastSortByExpression"] = e.SortExpression;
        GVStudentList.Attributes["LastSortByOrder"] = e.SortDirection.ToString();

        GVStudentList.DataSource = dv;
        GVStudentList.DataBind();
    }

    protected void GVStudentList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        GVStudentList.PageIndex = e.NewPageIndex;
        DataSet ds = DataSource.GetData();
        DataView dv = ds.Tables[0].DefaultView;
        GVStudentList.DataSource = dv;
        GVStudentList.DataBind();
    }

    protected void GVStudentList_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
    {
        GridView gvTemp = (GridView)sender;

        int studentNumber = int.Parse(gvTemp.Rows[e.NewSelectedIndex].Cells[2].Text);
        string studentName = string.Format("{0} {1} {2} {3}",
            gvTemp.Rows[e.NewSelectedIndex].Cells[3].Text,
            gvTemp.Rows[e.NewSelectedIndex].Cells[5].Text,
            gvTemp.Rows[e.NewSelectedIndex].Cells[6].Text,
            gvTemp.Rows[e.NewSelectedIndex].Cells[4].Text);
        lblSelectedStudentNumber.Text = studentNumber.ToString();
        lblSelectedStudentName.Text = studentName;
    }


    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        //get image from source
        if (fpStudentPhoto.FileContent != null)
        {
            using (SqlConnection conn = new SqlConnection("Data Source=EIL-SW-DSK-063;Initial Catalog=Test_eMinerva4_6;User ID=sa; password=sqlpassword76"))
            {
                using (SqlCommand cmd = new SqlCommand())
                {
                    cmd.CommandText = "UPDATE Student SET StudentPhoto = @Image Where StudentNo = @StudentNumber";
                    cmd.Parameters.AddWithValue("@Image", fpStudentPhoto.FileBytes);
                    cmd.Parameters.AddWithValue("@StudentNumber", int.Parse(lblSelectedStudentNumber.Text));
                    cmd.CommandType = CommandType.Text;
                    cmd.Connection = conn;
                    conn.Open();
                    int rowEffected = cmd.ExecuteNonQuery();
                }
            }
        }
        else { lblMessage.Text = "Please select image"; }
    }
}

Remember to create your datasource I just used a student database for example.

I also have been attempting to do this and now have the handler to render the image bytes into the response stream so I can add and view images. BUT, for updating an existing row containing an image I'm using the gridview's update link to show the fileuploader in the cell but then I'm lost as to how to get the chosen file automatically stored in the db by the grid's update event. Can this be done or do I need to write separate code just for doing the sql update for the image field? That would be crazy as the grid knows how to update the other fields.

hi frnds,I have two images data into the databse,First one is Sunset & second one is Winter(From My pictures)...Mine code is now able to retrive the image from the databse,,& show it in Gridview..But probs is that instead of two images One Sunset & second winter..It is displaying two Sunset Images..I m posting the code below--

Plz
help me out-----
Insertion Code

public partial class _Default : System.Web.UI.Page 
{
    string query;
    SqlConnection conn = new SqlConnection("Data Source=SONIA-B408A4159\\SQLEXPRESS;Initial catalog=sonia;Integrated Security=true");

  
    protected void Button1_Click(object sender, EventArgs e)
    {

        if (FileUpload1.PostedFile.FileName == null
|| FileUpload1.PostedFile.FileName == "")
        {
            lblErrors.Text = "Please Select the file";
                  }
        else
        {
         byte[] myimage = new byte[FileUpload1.PostedFile.ContentLength]; 
HttpPostedFile Image = FileUpload1.PostedFile; 
Image.InputStream.Read(myimage, 0, (int)FileUpload1.PostedFile.ContentLength);

query = "Insert into ImageGallery1 values(@image1)";
//query = "Insert into NewImageGallery values(@imgData,@imgtype,@imgLength)";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("@image1", myimage);
//cmd.Parameters.AddWithValue("@imgtype", FileUpload1.PostedFile.ContentType);
//cmd.Parameters.AddWithValue("@imgLength", FileUpload1.PostedFile.ContentLength);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
        }
      
    }

RETRIEVAL CODE_

public partial class Default2 : System.Web.UI.Page
{
   
    SqlConnection conn = new SqlConnection("Data Source=SONIA-B408A4159\\SQLEXPRESS;Initial catalog=sonia;Integrated Security=true");
   

    protected void Page_Load(object sender, EventArgs e)
    {
        GridView1.DataSource = FetchAllImagesInfo();
GridView1.DataBind();
        
         }

    public DataTable FetchAllImagesInfo()
{
  string sql = "Select * from ImageGallery1";
  SqlDataAdapter da = new SqlDataAdapter(sql, conn); 
  DataTable dt = new DataTable(); 
  da.Fill(dt); 
  return dt;
}
     }

SOURCE TAB-

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:TemplateField HeaderText="Template">
                <itemtemplate>
                 <asp:Image ID="Image1" runat="server" ImageUrl="~/GetDBImage.ashx" />
                </itemtemplate>
                </asp:TemplateField>
                                </Columns>
        </asp:GridView>

ASHX PAGE

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

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

public class GetDBImage : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        SqlConnection conn = new SqlConnection("Data Source=SONIA-B408A4159\\SQLEXPRESS;Initial catalog=sonia;Integrated Security=true");
        conn.Open();
       string  query = "select * from ImageGallery1";
      SqlCommand  cmd = new SqlCommand(query, conn);
     SqlDataReader  dr = cmd.ExecuteReader();
       while (dr.Read())
       {
           int contentlength = Convert.ToInt32(dr.GetBytes(0, 0, null, 0, int.MaxValue));
           byte[] buffer = new byte[contentlength];
           dr.GetBytes(0, 0, buffer, 0, contentlength);
           context.Response.BinaryWrite(buffer);
           context.Response.End();  
       }
       }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}

DATABASe-

create table ImageGallery1(image1 image)
select * from ImageGallery1
delete from ImageGallery1

Hi,

Try query as

select distinct * from imagegallery

Check whether you have uplaoded two seperate images.

The RbmBinaryImage control will help you display images directly from your database. You could bind the Image field directly to the ImageContent property, also you could specify whether you want the display to be as a thumbnail or not and provide the thumbnail size.

to get it go to http://www.ramymostafa.com/?p=187

Regards
Ramy Mostafa

I want to insert the image into database & Retrive the data back & display into DataGridView..


Foll is the code the inserts the image data into Databse--

protected void Button1_Click(object sender, EventArgs e)
    {

        if (FileUpload1.PostedFile.FileName == null
|| FileUpload1.PostedFile.FileName == "")
        {
            lblErrors.Text = "Please Select the file";
                  }
        else
        {
         byte[] myimage = new byte[FileUpload1.PostedFile.ContentLength]; 
HttpPostedFile Image = FileUpload1.PostedFile; 
Image.InputStream.Read(myimage, 0, (int)FileUpload1.PostedFile.ContentLength);

query = "Insert into ImageGallery1 values(@Image_Content)";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.Parameters.AddWithValue("@Image_Content", myimage);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();

        }
           }

I drag the Grdview onto the second form--

SOURCE TAB

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <Columns>
                <asp:TemplateField HeaderText="Template">
                <itemtemplate>
                 <asp:Image ID="Image1" runat="server"  /> 
                </itemtemplate>
                </asp:TemplateField>
                                </Columns>
        </asp:GridView>

Foll code raed the binary data from the database,but mine code is displaying image on page load-

public partial class Default2 : System.Web.UI.Page
{
    string query;
    SqlConnection conn = new SqlConnection("Data Source=SONIA-B408A4159\\SQLEXPRESS;Initial catalog=sonia;Integrated Security=true");
    SqlDataReader dr;
    SqlCommand cmd;

    protected void Page_Load(object sender, EventArgs e)
    {
        query = "select * from ImageGallery1";
        conn.Open();
        cmd=new SqlCommand (query ,conn );
        dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            int contentlength = Convert .ToInt32 (dr.GetBytes(0, 0, null, 0, int.MaxValue));
            byte[] buffer = new byte[contentlength];
            dr.GetBytes(0, 0, buffer, 0, contentlength);
            Response.BinaryWrite(buffer); 

        }


    }
}

I do not know how to insert image into Gridview,Can somebody tell me how to do that??//

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.