Forums » .NET » ASP.NET »

How to Display Image in Gridview From database without using Handler file ?


Posted Date: 16 Apr 2012      Posted By:: dvendra yadav     Member Level: Bronze    Member Rank: 2876     Points: 1   Responses: 2



How to Display Image in Gridview From database without using Handler file ?

Note: Image is Binary format on database




Responses

#666557    Author: NISHAD      Member Level: Silver      Member Rank: 364     Date: 16/Apr/2012   Rating: 2 out of 52 out of 5     Points: 4

here given example is in vb code you can convert it as per your req.
First of all take image field from designing side and have to add column for image field as below:-

<asp:GridView ID="GD1" runat="server" AutoGenerateColumns="False"
ShowHeader="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Image ID="imgSaved" Height="150" Width="125" runat="server" ImageUrl='<%# imageURL(DataBinder.Eval(Container.DataItem, "Rno")) %>'
AlternateText='<%#DataBinder.Eval(Container.DataItem,"img_title") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>


---------------------------------------------------------------------

'THEN DO CODING IN LOAD EVENT OF CODING PAGE OF VB OR C# LIKE THESE



Public Sub displayImages()
Try
If btnSubmit.Text = "Verify" Then
str1 = "select Rno,img_title,img_type,img_stream from reg_master where Rname ='" + name + "'AND Remail = '" + txtEmail.Text + "'"
Else
str1 = "select Rno,img_title,img_type,img_stream from reg_master where Rname = " + Label19.Text
End If

cmd.CommandType = Data.CommandType.Text
cmd.CommandText = str1
cmd.Connection = con
Dim myAdapter As New OleDbDataAdapter(cmd)
Dim myDataSet As New DataSet
myAdapter.Fill(myDataSet)
GD1.DataSource = myDataSet
GD1.DataBind()


Catch ex As Exception
End Try
End Sub
----------------------------------FOR IMAGE URL------------------
Public Function imageURL(ByVal img_id) As String
Return ("retrieveImages.aspx?id=" & img_id)
End Function


 
#666629    Author: Ravindran        Member Level: Diamond      Member Rank: 3     Date: 16/Apr/2012   Rating: 2 out of 52 out of 5     Points: 4

Without handler you can use dummy page to write image in gridview

i have table like this

create table stud([ID] [int] IDENTITY(1,1) ,sname varchar(50),simage image)


Default.aspx Client side
      
<asp:ValidationSummary ID="ValidationSummary1" runat="server" HeaderText="Page has following Error" ValidationGroup="edit"/><br/>
<asp:ValidationSummary ID="ValidationSummary2" runat="server" HeaderText="Page has following Error" ValidationGroup="new"/> <br/>
Enter Student Name <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br/>
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" ErrorMessage="Student Name cannot be blank!" ControlToValidate="TextBox1" Display="None" ValidationGroup="new" ></asp:RequiredFieldValidator>
Select student image to be uploaded<asp:FileUpload ID="FileUpload1" runat="server" /><br/>
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server" ErrorMessage="Select image to be upload!" ControlToValidate="FileUpload1" Display="None" ValidationGroup="new" ></asp:RequiredFieldValidator><br/>
<asp:Button ID="Button1" runat="server" Text="Add New Student" onclick="Button1_Click" ValidationGroup="new" /><br/>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
DataKeyNames="sid" onrowcancelingedit="GridView1_RowCancelingEdit"
onrowdeleting="GridView1_RowDeleting" onrowediting="GridView1_RowEditing"
onrowupdating="GridView1_RowUpdating"
onpageindexchanging="GridView1_PageIndexChanging">
<Columns>
<asp:TemplateField HeaderText="Student name">
<ItemTemplate>
<%#Eval("sname")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtsname" runat="server" Text='<%#Bind("sname")%>'></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="Student Name cannot be blank!" ControlToValidate="txtsname" Display="None" ValidationGroup="edit" ></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Student image">
<ItemTemplate>
<%--using normal .aspx page convert bytes to image--%>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# "Default3.aspx?ID=" + Eval("sid")%>' Height="100" Width="120"/>

<%--using handler convert bytes to image--%>
<%--<asp:Image ID="Image2" runat="server" ImageUrl='<%# "Handler2.ashx?ID=" + Eval("sid")%>' runat="server" Height="100" Width="150"/>--%>
</ItemTemplate>
<EditItemTemplate>
<asp:FileUpload ID="FileUpload2" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" ErrorMessage="Student image cannot be blank!" ControlToValidate="FileUpload2" Display="None" ValidationGroup="edit"></asp:RequiredFieldValidator>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Modify" ShowEditButton="true" EditText="Edit" ValidationGroup="edit">
<ControlStyle Width="50" />
</asp:CommandField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton ID="lnkDelete" CommandName="Delete" runat="server" OnClientClick="return confirm('Are you sure you want to delete this record?');"
>Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>


Default.aspx.cs code

using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Configuration;
public partial class _Default : System.Web.UI.Page
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
String sname, query;
byte[] filebyte = null;

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadGrid();
}
Button1_Click(this, new EventArgs());
}
void LoadGrid()
{
sqlcon.Open();
sqlcmd = new SqlCommand("select * from stud", sqlcon);
da = new SqlDataAdapter(sqlcmd);
dt.Clear();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
else
{
GridView1.DataBind();
}
sqlcon.Close();
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
sname = TextBox1.Text;
filebyte = convertByte(FileUpload1);
sqlcon.Open();
query = "insert into stud(sname,simage) values(@sname,@simage)";
SqlCommand cmd = new SqlCommand(query, sqlcon);
cmd.Parameters.Add("@sname", SqlDbType.VarChar).Value = sname;
cmd.Parameters.Add("@simage", SqlDbType.Image).Value = filebyte;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
sqlcon.Close();
TextBox1.Text = "";
LoadGrid();
}
}
public byte[] convertByte(FileUpload FileControl)
{
Stream fs = default(Stream);
byte[] bytes1 = null;
byte[] postfile = null;
fs = FileControl.PostedFile.InputStream;
BinaryReader br1 = new BinaryReader(fs);
bytes1 = br1.ReadBytes(FileControl.PostedFile.ContentLength);
postfile = bytes1;
return postfile;
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
String sid;
sid = GridView1.DataKeys[e.RowIndex].Value.ToString();
sqlcmd = new SqlCommand("delete from stud where sid='" + sid +"'", sqlcon);
sqlcon.Open();
sqlcmd.CommandType = CommandType.Text;
sqlcmd.ExecuteNonQuery();
sqlcon.Close();
LoadGrid();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
LoadGrid();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
LoadGrid();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
string sid;
sid = GridView1.DataKeys[e.RowIndex].Value.ToString();

TextBox sname = (TextBox)row.FindControl("txtsname");
FileUpload simage = (FileUpload)row.FindControl("FileUpload2");

sqlcon.Open();
query = "update stud set sname=@sname,simage=@simage where sid=@sid";
SqlCommand cmd = new SqlCommand(query, sqlcon);
cmd.Parameters.Add("@sname", SqlDbType.VarChar).Value = sname.Text;
cmd.Parameters.Add("@simage", SqlDbType.Image).Value = convertByte(simage);
cmd.Parameters.Add("@sid", SqlDbType.Int).Value = Convert.ToInt32(sid);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
sqlcon.Close();
GridView1.EditIndex = -1;
LoadGrid();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
LoadGrid();
}
}


Default3.aspx.cs

using System.Data.SqlClient;
using System.Data;
using System.IO;


public partial class Default3 : System.Web.UI.Page
{
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
SqlCommand sqlcmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
DataSet ds = new DataSet();
byte[] b = null;

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
int sid = Convert.ToInt32(Request.QueryString["ID"]);
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["Con"].ConnectionString);
SqlCommand sqlcmd = new SqlCommand("Select simage from stud where sid =@sid", sqlcon);
sqlcmd.Parameters.Add("@sid", SqlDbType.Int).Value = sid;
sqlcmd.CommandType = System.Data.CommandType.Text;
sqlcon.Open();
da = new SqlDataAdapter(sqlcmd);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
b = ((byte[])dt.Rows[0][0]);
MemoryStream ms = new MemoryStream(b);
Response.ContentType = "image/jpeg";
Response.BinaryWrite(b);
}
}
}
}


Further more detail on this refer my DNS resource
http://www.dotnetspider.com/resources/42953-How-show-uploaded-images-Grid-view.aspx

Regards
N.Ravindran
Your Hard work never fails


 
Post Reply

 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.



Next : Uploading an file to SQL through an ASP.NET webform
Previous : Project of Social Networking Site.
Return to Discussion Forum
Post New Message
Category: ASP.NET

Related Messages

Subscribe to Subscribers
Active Members
Today
    Last 7 Daysmore...

    Awards & Gifts
    Talk to Webmaster Tony John
    Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India