Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Bind Image from Database to DataGrid (web Application)

0.00/5 (No votes)
30 Apr 2007 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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here