15.02.2015 Views

C# 4 and .NET 4

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

aDo.neT <strong>and</strong> Data Binding ❘ 1171<br />

Binding to the Database<br />

The two controls you are going to bind to data are attendeeList <strong>and</strong> roomList. Before you do this,<br />

you need to add SqlDataSource web server controls that map to the tables you want to access in the<br />

MeetingRoomBooker.mdf database. The quickest way to do this is to drag them from the toolbox onto<br />

the Default.aspx Web Form <strong>and</strong> configure them via the Configuration Wizard. Figure 40-10 shows how<br />

to access this wizard for a SqlDataSource control.<br />

figure 40-10<br />

From the first page of the data source Configuration Wizard, you need to select the connection to the<br />

database created earlier. Next, choose to save the connection string as MRBConnectionString; then choose<br />

to select * (all fields) from the Attendees table in the database.<br />

After completing the wizard, change the ID of the SqlDataSource control to MRBAttendeeData. You also<br />

need to add <strong>and</strong> configure two more SqlDataSource controls to obtain data from the Rooms <strong>and</strong> Events<br />

tables, with ID values of MRBRoomData <strong>and</strong> MRBEventData respectively. For these subsequent controls, you<br />

can use the saved MRBConnectionString for your connection.<br />

After you’ve added these data sources, you will see in the code for the form that the syntax is very simple:<br />

<br />

<br />

<br />

code snippet PCSWebSite3/Default.aspx<br />

The definition of the connection string in use is found in the web.config file, which we look at in more<br />

detail later in this chapter.<br />

Next, you need to set the data-binding properties of the roomList <strong>and</strong> attendeeList controls. For<br />

roomList the settings required are as follows:<br />

➤<br />

➤<br />

➤<br />

DataSourceID — MRBRoomData<br />

DataTextField — Room<br />

DataValueField — ID<br />

And, similarly, for attendeeList:<br />

➤<br />

➤<br />

➤<br />

DataSourceID — MRBAttendeeData<br />

DataTextField — Name<br />

DataValueField — ID<br />

You can also remove the existing hard-coded list items from the code for these controls.<br />

Running the application now will result in the full attendee <strong>and</strong> room data being available from your databound<br />

controls. You will use the MRBEventData control shortly.<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!