data binding in asp

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.

Upload: 28051970

Post on 09-Apr-2018

229 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Data Binding in ASP

8/7/2019 Data Binding in ASP

http://slidepdf.com/reader/full/data-binding-in-asp 1/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 canenhance 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 toemploy 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 isbeing 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 underApp_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 thefirst row under the "Complete" status.

Page 2: Data Binding in ASP

8/7/2019 Data Binding in ASP

http://slidepdf.com/reader/full/data-binding-in-asp 2/19

 

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 aneditable 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>

Page 3: Data Binding in ASP

8/7/2019 Data Binding in ASP

http://slidepdf.com/reader/full/data-binding-in-asp 3/19

  </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 thedatabase "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 bindingtechniques 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.

Page 4: Data Binding in ASP

8/7/2019 Data Binding in ASP

http://slidepdf.com/reader/full/data-binding-in-asp 4/19

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 isSqlDataSource2.

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.

Page 5: Data Binding in ASP

8/7/2019 Data Binding in ASP

http://slidepdf.com/reader/full/data-binding-in-asp 5/19

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 thedatabase. 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 thedatabase.

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 li st, try creating a separate table in the database listing only those choices. This can comeup 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 dropdown 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 candownload the entire Default.aspx source code for this tutorial.

Page 6: Data Binding in ASP

8/7/2019 Data Binding in ASP

http://slidepdf.com/reader/full/data-binding-in-asp 6/19

DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainmentand/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 employreal-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing anyinformation 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 MSSQL 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 appearedyesterday.

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. Fi rst create a project in Visual Web Developer. (From the Start Page Create Website) The projectinformation 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 tableshould look like this:

Page 7: Data Binding in ASP

8/7/2019 Data Binding in ASP

http://slidepdf.com/reader/full/data-binding-in-asp 7/19

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 serverdatabase.

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 )

Page 8: Data Binding in ASP

8/7/2019 Data Binding in ASP

http://slidepdf.com/reader/full/data-binding-in-asp 8/19

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 beable to delete and edi t/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 bevalidated 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 datainserting 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>

Page 9: Data Binding in ASP

8/7/2019 Data Binding in ASP

http://slidepdf.com/reader/full/data-binding-in-asp 9/19

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

Page 10: Data Binding in ASP

8/7/2019 Data Binding in ASP

http://slidepdf.com/reader/full/data-binding-in-asp 10/19

  </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 shouldbe separately validated by assigning them a unique validation group. For example, INSERT is using ValidationGroup="Insertvalidation" while UPDATE/EDIT isusing 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 validationgroup 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>

Page 11: Data Binding in ASP

8/7/2019 Data Binding in ASP

http://slidepdf.com/reader/full/data-binding-in-asp 11/19

  <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 )

Page 12: Data Binding in ASP

8/7/2019 Data Binding in ASP

http://slidepdf.com/reader/full/data-binding-in-asp 12/19

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:

Page 13: Data Binding in ASP

8/7/2019 Data Binding in ASP

http://slidepdf.com/reader/full/data-binding-in-asp 13/19

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 entertainmentand/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 employreal-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing anyinformation 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 importantfeatures lets you display images retrieved from the database. These images are then rendered in the browser using the HTML image tag. This tutorial will showyou 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:

Page 14: Data Binding in ASP

8/7/2019 Data Binding in ASP

http://slidepdf.com/reader/full/data-binding-in-asp 14/19

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 Serverdatabase.

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 thissample/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 toprovide a table name, enter ai rcrafttable.

Now that the table has been successfully created, it is time to enter database records. To do this, right cl ick on “aircrafttable” under Tables in Database Explorerand 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. Pleasedownload 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:

Page 15: Data Binding in ASP

8/7/2019 Data Binding in ASP

http://slidepdf.com/reader/full/data-binding-in-asp 15/19

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 importantrequirements.

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 astheir 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 soon 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 pixelssize.

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 WebDeveloper):

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:

Page 16: Data Binding in ASP

8/7/2019 Data Binding in ASP

http://slidepdf.com/reader/full/data-binding-in-asp 16/19

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 contentsof 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:

Page 17: Data Binding in ASP

8/7/2019 Data Binding in ASP

http://slidepdf.com/reader/full/data-binding-in-asp 17/19

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 -> EditColumns 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 clickAdd.

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 ImageFieldshould look like this:

Page 18: Data Binding in ASP

8/7/2019 Data Binding in ASP

http://slidepdf.com/reader/full/data-binding-in-asp 18/19

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" />

Page 19: Data Binding in ASP

8/7/2019 Data Binding in ASP

http://slidepdf.com/reader/full/data-binding-in-asp 19/19

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