Display the image in the database in GridView

xiaoxiao2021-03-14  202

Many people have this question, and the imagefield in the GridView control does not have a DataField property, so how can I bind to the image field in SQL Server? This has a problem since the DynamicImage control disappears from Beta2. However, asp.net2.0 also brought us another solution, which is convenient to use httphandler (.ashx) to dynamically display images in the database, this is available in the VS2005. Given the program: A image data in the database is dynamically obtained through ASHX, then place an image control in a custom template such as GridView and other controls, and set the ImageURL property of the image control to XXX.ashx? PhotoID = 1 image.

The following is the code of Handler.ashx:

<%

@WebHandler Language

=

"

C #

"

Class

=

"

Handler

"

%>

Using

System;

Using

System.data;

Using

System.data.sqlclient;

Using

System.IO;

Using

System.Web;

Using

System.configuration;

public

Class

Handler: IHTTPHANDLER

...

{

Public bool isreusable ... {

Get ... {

Return True;

}

}

Public void processRequest (httpcontext context) ... {

// set up the response settings

Context.response.contentType = "image / jpeg";

Context.Response.cache.setcacheability.public);

Context.Response.bufferoutput = false;

INT photoID = -1;

Stream stream = null;

IF (Context.Request.QueryString ["PhotoID"]! = NULL &&

Context.Request.QueryString ["photoid"]! = "") ... {

Photoid = Convert.Toint32 (Context.Request.QueryString ["PhotoID"]);

Stream = getPhoto (PhotoID);

}

Const int buffersize = 1024 * 16;

BYTE [] Buffer = New byte [buffersize];

INT count = stream.read (buffer, 0, buffersize);

While (count> 0) ... {

Context.Response.outputStream.write (buffer, 0, count);

Count = stream.read (buffer, 0, buffersize);

}

}

Public stream getphoto (int photoid) ... {

SqlConnection MyConnection = New SqlConnection

ConfigurationManager.connectionstrings ["Personal"]. Connectionstring; sqlcommand mycommand = new SQLCommand

("SELECT [bytesoriginal] from [photos] where [photoid] = @photoid",

MyConnection);

Mycommand.commandtype = commandtype.text;

MyCommand.Parameters.Add ("@photoid");

MyConnection.open ();

Object result = mycommand.executescalar ();

Try ... {

Return New MemoryStream ((byte []) Result;

}

Catch (argumentnullexception e) ... {

Return NULL;

}

Finally ... {

MyConnection.Close ();

}

}

}

Then define the template column in GridView:

<

ASP: Templatefield

>

<

ItemTemplate

>

<

ASP: Image

Id

= "Image1"

Runat

= "Server"

ImageURL

= '<% #

"HANDLER.ASHX? PhotoID

= " EVAL ("

PhotoID ")%

>

'/>

ItemTemplate

>

ASP: Templatefield

>

This allows you to display image type image data in the database in GridView. In fact, the Stater Kit comes with the VS2005 is useful, in addition, there are several other Club Web Site Starter Kit, etc., can be uploaded in ASP.NET.

转载请注明原文地址:https://www.9cbs.com/read-129441.html

New Post(0)