You are on page 1of 19

Data Binding in ASP.NET 3.

5 with a Basic Example


(Page 1 of 5 )

Data binding is a method of “binding” ASP.NET 3.5 web controls and the database column fields. This method of binding is necessary to produce a certain level of
interactivity within the web control. This article will explain how and why to use data binding in your web applications.

Data binding is more common in template-based ASP.NET web development (after converting bound fields to template fields). This is where a developer can
enhance or modify the default configuration of basic web control output to a more advance design.

For example, in an editable gridview, a text box field is employed to let the user type that the status of a project is either "Ongoing" or "Complete."

If you are going to change this textbox into a drop down list so that the user can just select either "Complete" or "Ongoing" using a dropdown, then you need to
employ data binding techniques with a drop down list.

You can then apply the principles illustrated in this tutorial to other web controls, not only drop down lists but check boxes and radio buttons as well.

Data Binding in ASP.NET 3.5 with a Basic Example - Create a database


(Page 2 of 5 )

Create a new website project in Visual Web Developer Express and name the project databindingexample. In the screen shot you'll see at the link, the project is
being saved in Drive E of the hard drive under the folder "aspdotnetprojects." You can select your own path and folder.

Next, create the worktodo.mdf database based on yesterday's tutorial, Using ASP.NET 3.5 ListView in a Web Application. You need to create the database under
App_Data, using the table name "tasklists." Right clicking on the tasklists and clicking "Show table data" will show the four default records in it. Try to put the
first row under the "Complete" status.
Once you see the complete table records, the database has been successfully created.

Create SqlDataSource and Editable Gridview

In the tutorial mentioned above, the project was created using the ListView web control. However, to make the data binding easy, you will need to use an
editable gridview, which by default uses a boundfield; converting it to a templatefield will make the work and data binding simpler.

But first, add a SqlDataSource and Gridview web control to the Default.aspx source code (click and drag it from View  Toolbox  Data).

Below is the resulting markup:

<%@ 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>

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

<div>

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

<asp:GridView ID="GridView1" runat="server">

</asp:GridView>
</div>

</form>

</body>

</html>

Data Binding in ASP.NET 3.5 with a Basic Example - Configure SqlDataSource and Editable Gridview
(Page 3 of 5 )

Go to Design View in Visual Web Developer. Right click on SqlDataSource  Show Smart tag  Configure Data Source. Under Data connection, select the
database "worktodo.mdf.

Check "Yes, save this connection" and then click next. You will then see the area where you will configure the Select Statement. Follow the steps below.

• Check "Specify columns from a table or view."

• Under name, select "tasklists."

• Under Columns, select "*".

• Click "Advanced"  check "Generate INSERT, UPDATE, and DELETE statements." Click OK.

• Click next and Finish the configuration.

Configure the gridview by right clicking on it and go to "Show Smart tag  Choose Data Source  SqlDataSource1"

Right click again  Show Smart Tag  and check the following:

a. Enable Paging

b. Enable Editing

c. Enable Deleting

Take a moment to look at the results in the browser by going to File  Browser.

However, when you click "Edit" you'll find it still uses a textbox under the "Status" column. You need to change this to a drop down list and use data binding
techniques to restore interaction with the database.

Data Binding in ASP.NET 3.5 with a Basic Example - Change the Textbox to a DropDownlist Control
(Page 4 of 5 )

Before you can implement data binding, you need to convert a boundfield into a template field. The rest of these important procedures are stated below.
Step 1. In the Design view, right click on the Gridview web control.

Step 2. Click "Show Smart tag"  Edit Columns.

Step 3. Select the "Status" field under "Selected Fields."

Step 4. Once the "Status" field has been highlighted, click the link "Convert this field into a TemplateField."

Step 5. Click OK.

The "Status" Column is now converted into a TemplateField. Your next job is to remove the textbox and replace it with a drop down list.

Step 6: Right click on the Gridview web control in Design view.

Step 7. Click "Show Smart Tag."

Step 8. Click "Edit Templates."

Step 9. Under "Display," select "EditItemTemplates."

What you will see is a textbox because that is what is currently being used as an input web control for the "Status" Column.

Step 10. Click the Textbox web control and hit the delete key. It will remove the textbox under "EditItemTemplate."

Step 11. Since you need the drop down list to interact with the database, drag a SqlDataSource first under EditItemTemplate. The SqlDataSource ID is
SqlDataSource2.

Step 12. You need to configure SqlDatasource2, by right clicking  Show Smart Tag  Configure data source.

Step 13. Under "Choose Data Connection," select "Connection String" and then click "Next."

Step 14. Configure using the following:

a. Check "Specify columns from a table or view."

b. Under table name, click "tasklists."

c. Under columns, check ONLY "Status." You only need to deal with one column, and that is the STATUS column.

d. Check also "Return only unique rows."

After setting the above configuration, click "Next" and hit "Finish."

Step 15. Once you have the SqlDataSource2 configured, drag the dropdownlist below SqlDataSource2.

Step 16. Right click on the DropDownlist, click "Show Smart tag"  "Choose Data Source"

Step 17. Under "Select Data Source," select SqlDataSource2.

Step 18. Under "data field to display" and "data field for the value," select "Status" for both.
Step 19. Click OK.

Your design view in Visual Web Developer with EditItemTemplate should look like this:

Data Binding in ASP.NET 3.5 with a Basic Example - Bind the DropDownlist to the Status Column in the MS SQL server database
(Page 5 of 5 )

Now that you have successfully replaced the text box with a drop down list for the "Status" field, you should now "bind" this web control to the Status field in the
database. To do this:

Step 1: Right click on the Dropdownlist web control under EditItemTemplate in Design view.

Step 2: Click "Edit Databindings."

Step 3: Under Bindable properties, select "SelectedValue."

Step 4: Select Field Binding and then, under "Bound to:" select "Status."

Step 5: Make sure "Two-way databinding" is checked. This will ensure that the user can not only retrieve data from database, but also write information to the
database.

Step 6: Click OK.

View the project in the browser again, and click the "Edit" link. The status column will now be replaced with a drop down list:

IMPORTANT: If you do not see the other choices under the drop down list, try creating a separate table in the database listing only those choices. This can come
up because, if a certain choice is not selected in all rows in the database, you cannot see it also as listed choices under the Status Column.

This is why we intend to put one record in the database with a "complete" status, so that you can see both the "complete" and "ongoing" choices in the drop
down list. If all status is "ongoing" then you can only see "ongoing" under the drop down list.

To remedy this problem, put the choices in a separate database table and use Foreign Key constraints. This will be covered in a separate tutorial. You can
download the entire Default.aspx source code for this tutorial.
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment
and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ
real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any
information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

Using ASP.NET 3.5 ListView in a Web Application


(Page 1 of 4 )

This tutorial will show an example of how to use the ListView web control, featuring data updating and validation, before the data is inserted or updated to the MS
SQL server database. Examples of how to use ListView controls to retrieve information from the data are featured in the first part of this tutorial, which appeared
yesterday.

Case Example: "Task to do" Web Application

Let's use ListView to make an ASP.NET 3.5 web application that will list all tasks in a table/spreadsheet format and let the user update, insert or delete tasks.

These tasks will be stored in the MS SQL server database. First create a project in Visual Web Developer. (From the Start Page  Create  Website) The project
information is listed below.

Location: File System

Path: {where would you like to save your project}, for example E:aspdotnetprojectsworktodo

Language: Visual Basic

Visual Studio Installed Templates: ASP.NET website

Click OK to create the website. After that, go to the Solutions Explorer. You need to create the database. Right click App_Data and then "Add New Item."

Here is the information needed:

Name: worktodo.mdf

Language: Visual Basic

Visual Studio Installed Templates: SQL Server Database

After creating the database, you need to create tables. Right click on Tables under Database Explorer, and then click "Add New Table." You then need to define
the Column Name, Data Type and Allow Nulls. Configure it according to the screen shot below:

Remember to set WorkID as the primary key index with increment and seed set to 1. Refer to this tutorial.

Using ASP.NET 3.5 ListView in a Web Application - Assign a table name: tasklists
(Page 2 of 4 )

Once the table has been created, you need to enter preliminary data. Download this Excel spreadsheet containing the raw data.

To enter those data manually, right click on the tasklist table under Database Explorer, and then click "Show Table Data." After entering the data, your table
should look like this:
Add SqlDataSource and ListView

Refer to part one for information on how to add SqlDataSource and ListView web controls from the Visual Web Developer toolbox and place them in Default.aspx.
After adding, the form tag in Default.aspx should look like this:

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

<div>

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

<asp:ListView ID="ListView1" runat="server">

</asp:ListView>

</div>

</form>

Go to the Design view in Visual Web Developer. Let's configure SqlDataSource to enable editing, updating and insertion of records to the MS SQL server
database.

Step 1. Right click on SqlDataSource  Show Smart tag  Configure Data Source  Select "worktodo.mdf" as the database. Now click Next.

Step 2. Check and save the connection string as "ConnectionString."

Step 3. Check "Specify Columns from a table or view."

Step 4. Under name, select the table name: "tasklists."

Step 5. Check "*" under Columns.

Step 6. Click "Advanced."

Step 7. Check "Generate INSERT, UPDATE and DELETE Statements."

Step 8. Click OK.

Step 9. Click Next and Finish.

Let's configure ListView to enable editing, updating and insertion of records to the database:

Step 1. Right click on ListView  Show Smart Tag  Choose Data Source  SqlDataSource1.

Step 2. Right click on Listview  Show Smart Tag  Configure ListView

Step 3. Select "Grid" under "Select a Layout."

Step 4. Select "No formatting" under "Select a style."

Step 5. Check  Enable Editing, Enable Inserting, Enable Deleting, Enable Paging. This can be found under "Options."

Step 6. Click OK.

Using ASP.NET 3.5 ListView in a Web Application - Input validation in the ListView Web Control
(Page 3 of 4 )
Go to File  View in Browser. What you will see should look like this screen shot.

Your "work to do" application is almost complete. You can see the various tasks in grid format, complete with status, date entered and deadline. Also you will be
able to delete and edit/update the records.

Another necessary function is to be able to insert new tasks into the database. However, since we are inserting and updating records, this data needs to be
validated to ensure its accuracy.

If you are new to ASP.NET 3.5 validation, it is recommended you read this complete tutorial series before proceeding further:

http://www.aspfree.com/c/a/ASP.NET/ASPNET-35-User-Input-Validation-Basics/

http://www.aspfree.com/c/a/ASP.NET/Validating-User-Input-with-ASPNET-35/

http://www.aspfree.com/c/a/ASP.NET/Completing-a-Basic-ASPNET-35-User-Input-Validation-Project/

Bear in mind that when you examine the generated source code of the project, the InsertItemTemplate as well as EditItemTemplate are in charge of data
inserting and editing. So this is where the validation controls will be added.

Since the InsertItemTemplate and EditItemTemplate fields can be validated similarly, we will illustrate an example using InsertItemTemplate.

Code Before Validation (InsertItemTemplate):

<InsertItemTemplate>

<tr style="">

<td>

<asp:Button ID="InsertButton" runat="server" CommandName="Insert"

Text="Insert" />

<asp:Button ID="CancelButton" runat="server" CommandName="Cancel"

Text="Clear" />

</td>
<td>

&nbsp;</td>

<td>

<asp:TextBox ID="WorkToDoTextBox" runat="server"

Text='<%# Bind("WorkToDo") %>' />

</td>

<td>

<asp:TextBox ID="StatusTextBox" runat="server" Text='<%# Bind("Status") %>' />

</td>

<td>

<asp:TextBox ID="DateEnteredTextBox" runat="server"

Text='<%# Bind("DateEntered") %>' />

</td>

<td>

<asp:TextBox ID="DeadlineTextBox" runat="server"

Text='<%# Bind("Deadline") %>' />

</td>

</tr>

</InsertItemTemplate>

Code withValidation (InsertItemTemplate) (using only RequiredFieldValidator to simplify examples)

<InsertItemTemplate>

<tr style="">

<td>

<asp:Button ID="InsertButton" runat="server" CommandName="Insert"

Text="Insert" causesvalidation="true" validationgroup="Insertvalidation" />

<asp:Button ID="CancelButton" runat="server" CommandName="Cancel"

Text="Clear" />

</td>

<td>

&nbsp;</td>

<td>

<asp:TextBox ID="WorkToDoTextBox" runat="server"

Text='<%# Bind("WorkToDo") %>' /><asp:RequiredFieldValidator ID="RequiredFieldValidator1"

runat="server" ErrorMessage="This is required do not leave blank." ControlToValidate="WorkToDoTextBox"


ValidationGroup="Insertvalidation"></asp:RequiredFieldValidator>
</td>

<td>

<asp:TextBox ID="StatusTextBox" runat="server" Text='<%# Bind("Status") %>' /><asp:RequiredFieldValidator ID="RequiredFieldValidator2"

runat="server" ErrorMessage="This is required do not leave blank." ControlToValidate="StatusTextBox"


ValidationGroup="Insertvalidation"></asp:RequiredFieldValidator>

</td>

<td>

<asp:TextBox ID="DateEnteredTextBox" runat="server"

Text='<%# Bind("DateEntered") %>' /><asp:RequiredFieldValidator ID="RequiredFieldValidator3"

runat="server" ErrorMessage="This is required do not leave blank." ControlToValidate="DateEnteredTextBox"


ValidationGroup="Insertvalidation"></asp:RequiredFieldValidator>

</td>

<td>

<asp:TextBox ID="DeadlineTextBox" runat="server"

Text='<%# Bind("Deadline")%>' /><asp:RequiredFieldValidator ID="RequiredFieldValidator4"

runat="server" ErrorMessage="This is required do not leave blank." ControlToValidate="DeadlineTextBox"


ValidationGroup="Insertvalidation"></asp:RequiredFieldValidator>

</td>

</tr>

</InsertItemTemplate>

There are two important points to remember concerning the code with validation.

First, since two important submission functions are available when communicating with the database (INSERT and UPDATE/EDIT), each of these functions should
be separately validated by assigning them a unique validation group. For example, INSERT is using ValidationGroup="Insertvalidation" while UPDATE/EDIT is
using ValidationGroup="Editvalidation."

Second, in addition to using ValidationGroup, the INSERT and UPDATE button in the form should be configured in such a way that it is clear what validation
group needs to be validated. For example:

INSERT Functionality (for InsertItemTemplate)

<asp:Button ID="InsertButton" runat="server" CommandName="Insert"

Text="Insert" causesvalidation="true" validationgroup="Insertvalidation" />

UPDATE/EDIT Functionality (for EditItemTemplate)

<asp:Button ID="UpdateButton" runat="server" CommandName="Update"

Text="Update" causesvalidation="true" validationgroup="Editvalidation"/>

Those two important highlights are applicable to both templates, <EditItemTemplate> and <InsertItemTemplate>

Code withValidation (EditItemTemplate) (using only the RequiredFieldValidator to simplify examples):

<EditItemTemplate>

<tr style="">

<td>
<asp:Button ID="UpdateButton" runat="server" CommandName="Update"

Text="Update" causesvalidation="true" validationgroup="Editvalidation"/>

<asp:Button ID="CancelButton" runat="server" CommandName="Cancel"

Text="Cancel" />

</td>

<td>

<asp:Label ID="WorkIDLabel1" runat="server" Text='<%# Eval("WorkID") %>' />

</td>

<td>

<asp:TextBox ID="WorkToDoTextBox" runat="server"

Text='<%# Bind("WorkToDo") %>' /><asp:RequiredFieldValidator ID="RequiredFieldValidator5"

runat="server" ErrorMessage="This is required do not leave blank." ControlToValidate="WorkToDoTextBox"


ValidationGroup="Editvalidation"></asp:RequiredFieldValidator>

</td>

<td>

<asp:TextBox ID="StatusTextBox" runat="server" Text='<%# Bind("Status") %>' /><asp:RequiredFieldValidator

ID="RequiredFieldValidator6" runat="server" ErrorMessage="This is required do not leave blank." ControlToValidate="StatusTextBox"


ValidationGroup="Editvalidation"></asp:RequiredFieldValidator>

</td>

<td>

<asp:TextBox ID="DateEnteredTextBox" runat="server"

Text='<%# Bind("DateEntered") %>' /><asp:RequiredFieldValidator ID="RequiredFieldValidator7"

runat="server" ErrorMessage="This is required do not leave blank." ControlToValidate="DateEnteredTextBox"


ValidationGroup="Editvalidation"></asp:RequiredFieldValidator>

</td>

<td>

<asp:TextBox ID="DeadlineTextBox" runat="server"

Text='<%# Bind("Deadline") %>' /><asp:RequiredFieldValidator ID="RequiredFieldValidator8"

runat="server" ErrorMessage="This is required do not leave blank." ControlToValidate="DeadlineTextBox"


ValidationGroup="Editvalidation"></asp:RequiredFieldValidator>

</td>

</tr>

</EditItemTemplate>

Of course, you can not only add the "RequiredFieldValidator," but you can also add other important types of validators to verify the correctness of information.
For example, you might add a CompareValidator to check the data type if the data entered in the "work to do" textboxes are in string format.

Using ASP.NET 3.5 ListView in a Web Application - Browser Test with Validation
(Page 4 of 4 )
Let's check this application using a web browser to see if our validation works as planned. In the first scenario, we'll try to update the first task, but leave the
"Status" column blank.

Result:

For our second scenario, we'll try to insert new data but leave the "WorkToDo" column blank. Do this, and then press "Insert."

Result:

For our third scenario, we'll try to insert new data without leaving anything blank.

Try entering this new record:

WorkToDo: Submit sitemap.xml to Google

Status: Ongoing

DateEntered:May 13, 2010

Deadline:May 15, 2010

Result:
For our fourth scenario, we'll try updating the first task (with WorkID =1) by changing the "Status" to complete.

Result:

You can download the complete project source code for Default.aspx. The MS SQL Server database used is discussed earlier in this article.

DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment
and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ
real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any
information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

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:


ASP.NET 3.5 GridView Images - Step 2: Import your Image folder to your ASP.NET folder
(Page 2 of 4 )

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.

ASP.NET 3.5 GridView Images - Step 3: Add and Configure SqlDataSource and the Gridview Web Control
(Page 3 of 4 )

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.

ASP.NET 3.5 GridView Images - Step 4: Add an ImageField to the Gridview Web Control
(Page 4 of 4 )

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>

You might also like