I have an application in which I store the image in binary form in a database and also display the image in a gridview control. I want to know how to display different images in multiple columns in a Gridview control.
Field in table
ImgId int
ImageName varchar
Image image
Image2 image
Default.aspx
<asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataKeyNames="ID" style="z-index: 103; left: 237px; position: absolute; top: 245px" Width="405px">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id"
InsertVisible="False" ReadOnly="True"
SortExpression="Id" />
<asp:BoundField DataField="ImageName" HeaderText="ImageName"
SortExpression="ImageName" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server"
ImageUrl='<%# Eval("ImgId", "Handler.ashx?ImgId={0}")+"&img=1"%>'/>
<asp:Image ID="Image2" runat="server"
ImageUrl='<%# Eval("ImgId", "Handler.ashx?ImgID={0}")+"&img=2"%>'/>
</ItemTemplate>
Default3.cs
Below code is for image insertion into the database in binary form
byte[] image = new byte[stream.Length];
stream.Read(image,0,image.Length);
SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\omar\Documents\Visual Studio 2005\WebSites\Project2\App_Data\Database.mdf;Integrated Security=True;User Instance=True");
string que = "insert into Pictures(Id,ImageName,Image)values('" + Session["Id"].ToString() + "',@imagename,@image )";
SqlCommand com = new SqlCommand(que, con);
com.Parameters.Add("@imagename", SqlDbType.VarChar, 500);
com.Parameters.Add("@image", SqlDbType.Image, image.Length);
com.Parameters["@imagename"].Value = strImageName.ToString();
com.Parameters["@image"].Value = image;
con.Open();
com.ExecuteNonQuery();
con.Close();
Response.Redirect("Default3.aspx");
Handle.ascx
using System;
using System.Web;
using System.Data.SqlClient;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string imageid = context.Request.QueryString["ImgId"];
SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\omar\Documents\Visual Studio 2005\WebSites\Project2\App_Data\Database.mdf;Integrated Security=True;User Instance=True");
SqlCommand com = new SqlCommand("Select ImageName,Image,Image2 From Pictures Where ImgId="+imageid,con);
con.Open();
SqlDataReader dReader = com.ExecuteReader();
dReader.Read();
int intImg = Convert.ToInt32(context.Request.QueryString["img"]);
if(intImg==1){
context.Response.BinaryWrite((byte[])dReader["Image"]);
}
if(intImg==2)
{
context.Response.BinaryWrite((byte[])dReader["Image2"]);
}
dReader.Close();
con.Close();