<asp:gridview id="GridView3" runat="server" autogeneratecolumns="False" datakeynames="IdBanner" xmlns:asp="#unknown">
EmptyDataText="No Record Found." ShowFooter="True" CellPadding="4"
ForeColor="#333333" GridLines="None" CellSpacing ="2" onrowcommand="GridView3_RowCommand" >
<rowstyle backcolor="#EFF3FB" />
<emptydatarowstyle bordercolor="Red" borderstyle="Double" forecolor="Red">
HorizontalAlign="Center" />
<columns>
<%--==========================================================================--%>
<asp:templatefield headertext="Id" visible="true">
<itemtemplate>
<asp:label id="lblId" runat="server" text="<%#Eval("Id") %>"></asp:label>
</itemtemplate>
</asp:templatefield>
<%-- ===================================================--%>
<asp:templatefield headertext="Image" itemstyle-horizontalalign="Left" headerstyle-horizontalalign="Left">
<edititemtemplate>
<asp:fileupload id="FileUploadEdit" runat="server" />
</edititemtemplate>
<itemtemplate>
<asp:image id="ImageIT" runat="server" width="40px" height="40px" imageurl="<%# "../Handler.ashx?IdBanner=" + Eval("IdBanner")%>" />
</itemtemplate>
<footertemplate>
<asp:fileupload id="FileUploadN" runat="server" />
</footertemplate>
</asp:templatefield>
<asp:templatefield headertext="" showheader="False">
<edititemtemplate>
<asp:linkbutton id="LinkButton1" runat="server" causesvalidation="True" commandname="Update" commandargument="<%# Container.DataItemIndex %>" onclientclick="return EditConfirmation();" tooltip="Update Record"></asp:linkbutton>
<asp:linkbutton id="LinkButton2" runat="server" causesvalidation="False" commandname="Cancel" commandargument="<%# Container.DataItemIndex %>" tooltip="Cancel Edit"></asp:linkbutton>
</edititemtemplate>
<itemtemplate>
<%--OnClick = "Edit"--%>
<asp:linkbutton id="lnkEdit" runat="server" text="" commandname="Edit" commandargument="<%# Container.DataItemIndex %>"></asp:linkbutton>
</itemtemplate>
<footertemplate>
<asp:linkbutton id="LinkButton2" runat="server" causesvalidation="False" commandname="AddNew" forecolor="White" tooltip="Add New Record"></asp:linkbutton>
</footertemplate>
</asp:templatefield>
<asp:templatefield headertext="" showheader="False">
<itemtemplate>
<asp:linkbutton id="LinkButton4" runat="server" causesvalidation="False" commandname="Delete" commandargument="<%# Container.DataItemIndex %>" tooltip="Eliminar Record">
</asp:linkbutton>
</itemtemplate>
</asp:templatefield>
</columns>
<footerstyle backcolor="#1A4D8A" font-bold="True" forecolor="White" />
<pagerstyle backcolor="#2461BF" forecolor="White" horizontalalign="center" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#1A4D8A" Font-Bold="True" ForeColor="White" />
<editrowstyle horizontalalign="Center" verticalalign="Middle" backcolor="#2461BF" />
<alternatingrowstyle backcolor="White" />
</emptydatarowstyle></asp:gridview>
Above is the Gridview Code in which i use Image control .For display image in this image control i use a Handler.below is the Handler.
handler.ashx
<![CDATA[<%@ WebHandler Language="C#" Class="Handler" %>]]>
using System;
using System.Web;
using System.Configuration;
using System.Data.SqlClient;
using System.Net;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["conm"].ConnectionString;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select Image from Banners where IdBanner=@IdBanner";
cmd.CommandType = System.Data.CommandType.Text;
cmd.Connection = con;
SqlParameter ImageID = new SqlParameter("@IdBanner", System.Data.SqlDbType.Int);
ImageID.Value = context.Request.QueryString["IdBanner"];
cmd.Parameters.Add(ImageID);
con.Open();
SqlDataReader dReader = cmd.ExecuteReader();
if (dReader.Read())
{
string impath = System.Web.HttpContext.Current.Server.MapPath("~/Images/no-image.gif");
if (string.IsNullOrEmpty(Convert.ToString(dReader["Image"])))
{
context.Response.ContentType = "image/jpg";
context.Response.BinaryWrite((byte[])ConvertImageFiletoBytes(impath));
}
else
{
context.Response.ContentType = "image/jpg";
context.Response.BinaryWrite((byte[])dReader["Image"]);
}
}
dReader.Close();
con.Close();
}
public bool IsReusable {
get {
return false;
}
}
public byte[] ConvertImageFiletoBytes(string ImageFilePath)
{
byte[] _tempByte = null;
if (string.IsNullOrEmpty(ImageFilePath) == true)
{
throw new ArgumentNullException("Image File Name Cannot be Null or Empty", "ImageFilePath");
return null;
}
try
{
System.IO.FileInfo _fileInfo = new System.IO.FileInfo(ImageFilePath);
long _NumBytes = _fileInfo.Length;
System.IO.FileStream _FStream = new System.IO.FileStream(ImageFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FStream);
_tempByte = _BinaryReader.ReadBytes(Convert.ToInt32(_NumBytes));
_fileInfo = null;
_NumBytes = 0;
_FStream.Close();
_FStream.Dispose();
_BinaryReader.Close();
return _tempByte;
}
catch (Exception ex)
{
return null;
}
}
}
Now you can write code for save image in database in bytes format on Gridview Row Command Event. Below is the Example.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AddNew")
{
FileUpload FileUploadN = (FileUpload)GridView3.FooterRow.FindControl("FileUploadN");
TextBox txtNEWLink = (TextBox)GridView3.FooterRow.FindControl("txtNEWLink");
BannerBean F = new BannerBean();
Int32 imglen = 0;
FileUpload imgK = (FileUpload)FileUploadN;
Byte[] imgByte = null;
if (imgK.HasFile && imgK.PostedFile != null)
{
HttpPostedFile File = FileUploadN.PostedFile;
imgByte = new Byte[File.ContentLength];
File.InputStream.Read(imgByte, 0, File.ContentLength);
}
F.ImgSize = imglen;
F.Image = imgByte;
F.Link = txtNEWLink.Text;
BannerDBManager dm = new BannerDBManager();
dm.AddBanner(F);
}
}
These values will pass to Business Object Class.
I m writting code for this class as example.
public void AddBanner(BannerBean F)
{
String cs = WebConfigurationManager.ConnectionStrings["conm"].ConnectionString;
SqlConnection conn = new SqlConnection(cs);
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = conn;
cmd.Parameters.Clear();
cmd.CommandType = CommandType.Text;
cmd.CommandText = " insert into Banner (Image,Link) values (@Image,@Link)";
if (string.IsNullOrEmpty(Convert .ToString (F.Image)))
{ cmd.Parameters.Add("@Image", SqlDbType.Image).Value = DBNull.Value; }
else
{ cmd.Parameters.Add("@Image", SqlDbType.Image).Value = F.Image; }
if (string.IsNullOrEmpty(F.Link))
{
cmd.Parameters.Add("@Link", SqlDbType.NVarChar).Value = DBNull.Value; }
else
{ cmd.Parameters.Add("@Link", SqlDbType.NVarChar).Value = F.Link; }
cmd.ExecuteNonQuery();
conn.Close();
}