Hi,
The Below Code is used to retrieve the Saved Images from the database inside the Grid view.
Write the following Code in Your aspx page
<asp:GridView ID="GridView1" runat="server" EnableViewState="false" AutoGenerateColumns="false">
<Columns>
<asp:BoundField HeaderText="AutoId" DataField="AutoId" />
<asp:BoundField HeaderText="File Name" DataField="FileName" />
<asp:TemplateField HeaderText="File">
<ItemTemplate> <img src="ShowImage.ashx?autoId=<%# Eval("AutoId") %>" alt="<%# Eval("FileName") %>" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="IsActive">
<ItemTemplate> <%# Eval("Active").ToString().Equals("True") ? "Yes" : "No" %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In Code Behind:
string _connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindFiles();
}
}
private void BindFiles()
{
DataTable table = new DataTable();
using (SqlConnection conn = new SqlConnection(_connStr))
{
string sql = "SELECT AutoId, FileName, FileContent, Active FROM Files Order By AutoID ASC";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
{
ad.Fill(table);
}
}
}
GridView1.DataSource = table;
GridView1.DataBind();
}
In the above cod, you can see that we have a GridView where we have specified BoundField and TemplateField on the .aspx page that is being bounded with the records from the database. Apart from FileContent, other fields can be specified as Text so to show the FileContent field that is of image type, we have used img html element and its src attribute has been specified as a Generic Handler (ShowImage.ashx file) that is being passed with the AutoId as the querystring. Below is the code snippet for the ShowImage.ashx generic handler.
Write thiscode in SHOWIMAGE.ASHX FILE (GenericHandler):
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
public class ShowImage : IHttpHandler {
public void ProcessRequest (HttpContext context)
{
if (context.Request.QueryString["autoId"] == null) return;
string connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ToString();
string autoId = context.Request.QueryString["autoId"];
using (SqlConnection conn = new SqlConnection(connStr))
{
using (SqlCommand cmd = new SqlCommand("SELECT FileContent FROM Files WHERE AutoID = @autoId", conn))
{
cmd.Parameters.Add(new SqlParameter("@autoId", autoId));
conn.Open();
using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
{
reader.Read();
context.Response.BinaryWrite((Byte[])reader[reader.GetOrdinal("FileContent")]);
reader.Close();
}
}
}
}
public bool IsReusable {
get {
return true;
}
}
}
Here, IsReUsable just notifies the application that the same instance of the handler should be reused or not. I hope this will help you.
Thanks & Regards,
Sandhya
Prabu_Spark, if this helps please login to Mark As Answer. | Alert Moderator