images from SQL to gridview

N

NuB

I have images stored in my SQL as .jpg and I want to show them in my Grid,
how can I do that? I've seen some examples, but they're pulling the images
from a folder not a database, I need to pull them directly from the
database.
 
H

Hans Kesting

I have images stored in my SQL as .jpg and I want to show them in my Grid,
how can I do that? I've seen some examples, but they're pulling the images
from a folder not a database, I need to pull them directly from the database.

You can't directly pull them from the database to show them in the
grid:
HTML doesn't allow you to "inline" the images.
The best you can do is to generate an <img> tag with a "src" attribute
(including parameters) pointing to a page that will output the data for
that single image (retrieved from the db), based on the parameters.

Some points of interest:
- set Response.ContentType (to the correct mimetype)
- maybe use Response.AppendHeader("Content-Disposition", "inline");
(possibly add ";filename=theimage.jpg;" to that "inline")
- use Response.BinaryWrite to write a byte[]
- if you use an aspx, don't have any (html) code in that aspx.

Hans Kesting
 
G

Guest

Please find an example below

1. My example Database stucture is as follows:
[FileId] UNIQUEIDENTIFIER PRIMARY CLUSTERED KEY
[Data] IMAGE NOT NULL

2. ViewImage.aspx.cs code
-- BEGIN CODE --
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

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

try
{
id = new Guid(Request.QueryString["id"]);
}
catch
{
// display a default image or message
// saying id is invalid
return;
}

this.AttachImageContent(id);

}

/// <summary>
///
/// </summary>
/// <param name="id"></param>
private void AttachImageContent(Guid id)
{
byte[] content = this.GetImageContent(id);

Response.ClearContent();
Response.ContentType = "image/jpg"; // get it from database
Response.OutputStream.Write(content, 0, content.Length);
Response.End();
}

private const string ConnectionString =
"server=(local);uid=;password=;" +
"database=BlobDatabase;pooling=true;max pool size=1;min pool size=1;";

/// <summary>
///
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
private byte[] GetImageContent(Guid id)
{
// should be a stored procedure
string query = "SELECT [Data] FROM [File] WHERE [FileId] = @FileId";

SqlConnection connection = new SqlConnection(ConnectionString);
SqlCommand command = new SqlCommand(query, connection);
SqlParameter parameter = new SqlParameter("@FileId",
SqlDbType.UniqueIdentifier);

parameter.Direction = ParameterDirection.Input;
parameter.Value = id;

command.CommandTimeout = 120;
command.CommandType = CommandType.Text;
command.Parameters.Add(parameter);

try
{
connection.Open();
return (byte[]) command.ExecuteScalar();
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (connection.State != ConnectionState.Closed)
connection.Close();
}

}
}

-- END CODE --

3. Aspx Page html code

-- BEGIN CODE --
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>

<!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>
<style type="text/css">
</style>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns=False>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<img
src='ViewImage.aspx?id=<%#DataBinder.Eval(Container.DataItem, "FileId")%>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="FirstName"/>
</Columns>
</asp:GridView>
</form>
</body>
</html>
-- END CODE --

4. Apsx behind c# code

-- BEGIN CODE --

using System;
using System.Data;
using System.Configuration;
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;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = GetDataSource();
GridView1.DataBind();
}

private DataTable GetDataSource()
{
DataTable table = new DataTable();

table.Columns.Add("FileId", typeof(string));
table.Columns.Add("FirstName", typeof(string));

DataRow row = table.NewRow();

row[0] = "e8302aa9-e82c-4d20-b3ae-79f8c5009dfb";
row[1] = "George W Bush";

table.Rows.Add(row);

return table;

}

}

-- END CODE --

Hope this helps
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top