Click here to Skip to main content
15,886,873 members
Articles / Web Development / ASP.NET
Article

Bind Image from Database to DataGrid (web Application)

Rate me:
Please Sign up or sign in to vote.
3.27/5 (11 votes)
29 Apr 2007CPOL3 min read 83.1K   1.5K   23   1
Handles uploading /downloading images into/from database to DataGrid

Introduction

In case of using image uploading and downloading from database, the following sample will help you. I came across examples which helped me to bind the image to a page with response's output stream. In some scenarios where image needs to be bound a column of a DataGrid,DataList,GridView you cant use the response stream. Here you need to save the images to some temporay folder for display. <asp:Image control can't be used to display the image, as the asp:Image control is rendered with encoded values (e.g C://My%20%Documents/My%20%Pictures) . To get rid of these problems I used normal Html image control and set the attribute "src" dynamically while binding the values.

In the sample given, the Image file is convert to byte array and stored in the DataBase with the file extension. While retrieveing the byte array is send to memory stream and stored in the temporay folder and displayed in grid .

Using the code

Database:

1. Create a Table with Image field as Varbinary(Max) and ImageType as varchar(20) in DataBase to store the image and image file extension respectively.

Sample Table

/****** Object: Table [transact].[TestImageStore] Script Date: 04/30/2007 11:50:40 ******/

CREATE

TABLE [transact].[TestImageStore](

[img] [varbinary]

(max) NULL,

[Image_Type] [varchar]

(20) NULL,

[imgID] [int]

IDENTITY(1,1) NOT NULL, CONSTRAINT [PK_TestImageStore] PRIMARY KEY CLUSTERED

(

[imgID]

ASC

)

ON [PRIMARY]

In Application :

Downloading and Binding the image to grid

1. Add a DataGrid to the aspx page.

2. Create TemplateColumn to place a Html image Control in it.

3. Set the attributes "ID" and "runat" and remove the attribute "src" from the Html image Control in the grid .

4. Get the result set values from database by executing the query statement.

5. Bind the result set to DataGrid.

6. In the Item Data Bound Event of the grid , get the binary value of image for each unique Id from result set .

i. Write the binary value into memory stream and store it in the temporary internet folder of the system.

ii. Set the url to attribute "src" of the Html image Control in the grid.

//
// In Aspx Page

<asp:DataGrid ID="dgBindImage" runat="server" AutoGenerateColumns="false" >

<Columns>

<asp:TemplateColumn HeaderText="Images">

<ItemTemplate >

<asp:Label ID="lblCode" Text='<%# Server.HtmlEncode(DataBinder.Eval(Container, "DataItem.imgID").ToString())%>' runat="server" />

<img id="imgPic" width="120" height="100" runat="server" />

</ItemTemplate>

</asp:TemplateColumn>

</Columns>

</asp:DataGrid>
//In code Behind
protected void dgBindImage_ItemDataBound(object sender, DataGridItemEventArgs e)

{

try

{

if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)

{

byte[] photoByte = null;

string PhotoExtension = string.Empty;

Label lblCode = (Label)e.Item.Cells[0].FindControl("lblCode");

HtmlImage img = (HtmlImage)e.Item.Cells[0].FindControl("imgPic");

if (dsInsp != null && img != null && lblCode != null && !string.IsNullOrEmpty(lblCode.Text))

{

//select each row from the local datatable with the ID

DataRow[] drowarr = dsInsp.Tables[0].Select("imgID=" + lblCode.Text);

DataRow dr = drowarr[0];

 

if (dr != null && dr["img"] != null && dr["Image_Type"] != null)

{

if (dr["img"] != DBNull.Value)

{

photoByte = (byte[])dr["img"];

}

PhotoExtension = dr["Image_Type"].ToString();

}

if (photoByte != null && photoByte.Length > 1)

{



System.Drawing.Image newImage;

//get the temporary internet folder path of the system to store the image file

string strFileName = UIUtilities.GetTempFolderName() + lblCode.Text.ToString() + PhotoExtension;



//write the binary data to memory stream 

using (MemoryStream stream = new MemoryStream(photoByte))

{

newImage = System.Drawing.Image.FromStream(stream);

//save the image file to temporary folder

newImage.Save(strFileName);

img.Attributes.Add("src", strFileName);

//lblAttachedFile.Text = strFileName; 



}



}

else

img.Attributes.Add("src", "");

}
//
<img src="ImageFromDBtoGrid/ImageFromDbToGrid.gif">

Uploading to Image to DB

1. Using the asp:fileUpload Control browse the image file.

2. Attach file (of any type .gif,.Jpg,.Doc) event read the uploaded file to binary data .

3. Store the binary value in a session object to make it persist across page's postbacks.

4. Get the extention of the image file and register it to hidden page control to make it persist across page's postbacks.

5. Set the values to parameters of the command object and insert into Database.

User Guide:

1. Click browse button to select a image file.

2. Click Attach link to attach the file .(You can find the attached file path at the below)

3. Click Save button to store it to the Database.

4. Click the view button to download and see the image in the grid.

(Note: the download file can be seen in the folder C:\Documents and Settings\<<UserName>>\Local Settings\Temporary Internet Files

class UIUtilities provides methods

1.To insert and retrieve the data into/from database.

2. Read the Image into binary data

3. To get the temporary internet folder name.

Conclusion

I hope these sample will help you in handling the Image files in your web pages. The same can be used in case of .rtf,.doc & etc.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralPoor performance Pin
Artem Smirnov7-May-07 23:40
professionalArtem Smirnov7-May-07 23:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.