ASP.NET 3.5 GridView Images

You might have learned how to put hyperlinks in the GridView in Tuesday’s tutorial on ASP.NET 3.5 GridView hyperlink columns. One of GridView’s important features lets you display images retrieved from the database. These images are then rendered in the browser using the HTML image tag. This tutorial will show you how to take advantage of this feature, which has several applications in e-commerce and online catalogs.

This tutorial has been written using ASP.NET 3.5 platform in Visual web developer express 2008. The database is using MS SQL server 2008 edition.

Step 1: Create project and sample database

Since information about images will be retrieved from the database, you need to create a practice database first before you can configure Gridview tables.

Before creating any database, you must create a project with Visual Web Developer using the following configuration:

a. In the start page, Create -> Website.

b. Under Visual Studio Installed Templates, select “ASP.NET website.”

c. Location and path: File system and select where you would like to save your ASP.NET project in your Windows hard drive. For example:

E:aspdotnetprojectsgridviewimagesproject

d. Language: Visual Basic

Finally, hit OK. Visual Web Developer will create the following files:

a. App_Data — this is where you will create and place your MS SQL server database.

b. Default.aspx — this is where all ASP.NET scripting or source code will be placed.

c. Default.aspx.vb — this is where you will place your Visual Basic server side coding (not needed in this tutorial).

d. web.config — this is the web configuration file (not needed in this tutorial).

To create the database, right click on App_Data under Solution Explorer. Click “Add new item,” then under Visual Studio installed templates, select SQL Server database.

Under name, use militaryaircraft.mdf, and then for the language, use Visual Basic and click “Add.” Right click on “Tables” and click “Add New Table.”

You will need to create the database fields or column name and its type. See the screen shot below for those fields and the types you need to create for this sample/test database:

Remember to set aircraftid as the primary key with the identity specification set to “Yes;” you can refer to this tutorial for details. 

Uncheck “Allow Nulls” because you are not going to allow nulls in your database records. Save all your files, and when Visual Web Developer prompts you to provide a table name, enter aircrafttable.

Now that the table has been successfully created, it is time to enter database records. To do this, right click on “aircrafttable” under Tables in Database Explorer and click “Show Table Data.”

You will be presented with four columns; however, you will only need to enter records in the following fields:

a. Name

b. Type

c. PrimaryUser

The aircraftid will be automatically incremented once the data has been successfully committed to the database, because it is used as the primary key. Please download this Excel worksheet containing the records to be entered into the MS SQL server database table. 

After entering all database records, it should look like this:

{mospagebreak title=Step 2: Import your Image folder to your ASP.NET folder}

Okay, the next thing we need to do is prepare your images and import them to your ASP.NET project folder. Your images and folder must satisfy three important requirements.

First, your file name must be consistent with your database records. For the purpose of this tutorial and for simplicity, we will name the image files the same as their aircraftid.

So the image file for the B-2 Spirit aircraft is 4.jpg (4 is the aircraft ID of B-2 Spirit in the MS SQL server database table), the A-10 Thunderbolt II is 1.jpg, and so on and so forth.

Second, the image size should be reasonable enough to be considered a thumbnail. Typically, the images used in this tutorial do not exceed the 300 x 300 pixels size.

Finally, you will need to place your folder in the ASP.NET folder. For example, if you use the path shown below (during the project creation in Visual Web Developer):

E:aspdotnetprojectsgridviewimages

Your ASP.NET folder is gridviewimages, which is also the name of your project. Place your image folder under this folder. The sample image folder used in this tutorial can be downloaded here: http://www.dotnetdevelopment.net/aircraftimages.zip

Unzip (right click, then “Extract here”) and put it in your ASP.NET folder. Here is an example:

In the above screen shot, you will see the gridviewimages ASP.NET project folder, and inside the folder is aircraftimages, which is the image folder. The contents of this folder are image thumbnails to be shown in the web browser using the gridview web control.

{mospagebreak title=Step 3: Add and Configure SqlDataSource and the Gridview Web Control}

Go to View -> Solution Explorer and then go to the source code of Default.aspx. Just under the <body> tag, enter this header:

<h2>Top US Military Aircraft</h2>

Click and drag  the SqlDataSource web control (View -> Toolbox -> Data -> SqlDataSource) and place it between the <div></div> tags.

Click and drag the Gridview web control (View -> Toolbox -> Data -> Gridview) and place it next to <asp:SqlDataSource ID="SqlDataSource1" runat="server"></asp:SqlDataSource>

To configure these two web controls easily, go to the Design view. This is how the Design view will look:

Right click on SqlDataSource and click “Configure Data Source.” Select “militaryaircraft.mdf” in the database to connect. Then click “Yes, save this connection as: ConnectionString.”

Select “Specify columns from a table or view” and check “*”. Click next and finish.

Right click on the Gridview web control -> Show Smart Tag -> Choose Data Source -> Select “SqlDataSource1”

The aircraftid needs to be removed from the gridview column because it is not important. Right click on the Gridview web control -> Show Smart Tag -> Edit Columns and under “Selected Fields,” select aircraftid and then press the delete button (red x). Finally, click OK.

{mospagebreak title=Step 4: Add an ImageField to the Gridview Web Control}

To add an imagefield, right click on the Gridview web control -> Show Smart Tag -> Edit Columns and under “Available fields,” select “Imagefield” and then click Add.

You need to place the ImageField next to the name field, so press the up button until it is next to the name field (refer to the screen shot below).

Under ImageField properties, configure the following:

DataImageUrlField: aircraftid

DataImageUrlFormatString: /gridviewimages/aircraftimages/{0}.jpg

HeaderText: Photo

The DataImageUrlfield is the database column field you need to associate with the filename of the image.

The DataImageUrlFormatString is the path to your image; the symbol {0} is grabbed from the database based on your DataImageUrlfield value.

The HeaderText is the name of the image column when shown to the web browser.

You can even format the table, by for example using “Autumn” in Autoformat. The Edit Column field should look like this:

After going through the “Edit Column” configuration, click OK. Finally, save your project and then go to File -> View in Browser. Your Gridview with ImageField should look like this:

Reference Project Source Code

Below is the generated source code for Default.aspx for this project:

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" 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></title>

</head>

<body>

<h2>Top US Military Aircraft</h2>

<form id="form1" runat="server">

<div>

<asp:SqlDataSource ID="SqlDataSource1" runat="server"

ConnectionString="<%$ ConnectionStrings:ConnectionString %>"

SelectCommand="SELECT * FROM [aircrafttable]"></asp:SqlDataSource>

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"

BackColor="White" BorderColor="#CC9966" BorderStyle="None" BorderWidth="1px"

CellPadding="4" DataKeyNames="aircraftid" DataSourceID="SqlDataSource1">

<RowStyle BackColor="White" ForeColor="#330099" />

<Columns>

<asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />

<asp:ImageField DataImageUrlField="aircraftid"

DataImageUrlFormatString="/gridviewimages/aircraftimages/{0}.jpg"

HeaderText="Photo">

</asp:ImageField>

<asp:BoundField DataField="type" HeaderText="type" SortExpression="type" />

<asp:BoundField DataField="primaryuser" HeaderText="primaryuser"

SortExpression="primaryuser" />

</Columns>

<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />

<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />

<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />

<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />

</asp:GridView>

</div>

</form>

</body>

</html>

[gp-comments width="770" linklove="off" ]