Binding Data to the User Interface

Binding Data to the User Interface

ASP.NET includes extremely flexible data-binding capabilities, many of which are discussed in the following sections.

Simple Data Binding

Simple data binding means connecting a user interface element to a single value from the data model. ASP.NET supplies a special syntax for binding ( <%# ... %> ). You can write any valid expression within <%# ... %> and the expression is evaluated when the DataBind() method of a control is called.

For example, the following code binds a property of the Calendar control with the value of an expression:

 <asp:Calendar id="calendar1" runat="server"           SelectedDate="<%# DateTime.Today.AddDays(1) %>"> 

Note that if you call the DataBind() method of the Page class as shown here, only a single call to the DataBind() method is sufficient to bind all the user interface elements on that page:

 private void Page_Load(object sender, System.EventArgs e) {     DataBind(); } 

You can also bind a property of one server control directly to a property of another server control. This provides an easy method to transfer information from one part of a Web form to another. For example, you can bind a Label control with a date selected in a Calendar control as shown here:

 <asp:Label id="lblInfo" runat="server" Visible="false" Text = '<%# calendar1.SelectedDate.ToShortDateString() %>' > </asp:Label> 

You can then program the SelectionChanged event of the Calendar control to bind the Label control when the date selection changes, as shown here:

 private void calendar1_SelectionChanged(object sender,  System.EventArgs e) {     lblInfo.Visible = true;     lblInfo.DataBind(); } 

Complex Data Binding

In complex data binding, you bind a user interface control to an entire collection of data, rather than to a single data item.

Binding to the List Controls

In this section, I discuss the data-binding capabilities of the controls derived from the System.Web.UI.WebControls.ListControls class, such as the CheckBoxList , DropDownList , ListBox , and RadioButtonList controls. These controls provide ways for the user to select one item from a list of data.

These controls can be bound to any collection that supports the IEnumerable , ICollection , or IListSource interface. This includes the ArrayList , HashTable , DataReader , and DataView classes.

In the following example, you'll use a complex data-bound ListBox in conjunction with a simple data-bound control such as a TextBox :

  1. Open Visual Studio .NET and create a new blank solution named 315C06 at c:\inetpub\ wwwroot \ExamCram (you might need to change the directory based on your configuration).

  2. Add a new Visual C# ASP.NET Web application at the following location: http://localhost/ExamCram/315C06/Example6_1 .

  3. Place a ListBox control ( lbExams ) and a Label control ( lblSelected ) on the Web form. Set the AutoPostBack property of the ListBox control to true , and set the Text property of the Label control to the following code:

     <%# lbExams.SelectedItemValue %> 
  4. Add a new Visual C# .NET class file named Exam.cs to the project and add the following code:

     using System; using System.Data; using System.Collections; public class Exam {     public ICollection DataLoad()     {        DataTable dtExam = new DataTable();        DataView dvExam;        DataRow drExam;        // Add two columns to the DataTable        dtExam.Columns.Add(new DataColumn("ExamNumber",            Type.GetType("System.String")));        dtExam.Columns.Add(new DataColumn("ExamName",           Type.GetType("System.String")));        // Put some data in        drExam = dtExam.NewRow();        drExam[0] = "70-315";        drExam[1] = "Developing Web Applications (Visual C# .NET)";        dtExam.Rows.Add(drExam);        drExam = dtExam.NewRow();        drExam[0] = "70-316";        drExam[1] = "Developing Windows Applications (Visual C# .NET)";        dtExam.Rows.Add(drExam);        drExam = dtExam.NewRow();        drExam[0] = "70-320";        drExam[1] =        "Developing Web services and Server Components (Visual C# .NET)";        dtExam.Rows.Add(drExam);        drExam = dtExam.NewRow();        drExam[0] = "70-305";        drExam[1] = "Developing Web Applications (Visual Basic .NET)";        dtExam.Rows.Add(drExam);        drExam = dtExam.NewRow();        drExam[0] = "70-306";        drExam[1] = "Developing Windows Applications (Visual Basic .NET)";        dtExam.Rows.Add(drExam);        drExam = dtExam.NewRow();        drExam[0] = "70-310";        drExam[1] = "Developing Web Services and Server Components (Visual Basic .NET)";        dtExam.Rows.Add(drExam);        // And return the datatable wrapped in a dataview        dvExam = new DataView(dtExam);        return dvExam;     } } 
  5. Double-click the Web form and add the following code in the Page_Load() event handler:

     private void Page_Load(object sender, System.EventArgs e) {     if(!IsPostBack)     {        // Create an Exam class object and call the DataLoad()        // method to assign it to the ListBox's DataSource        Exam exam = new Exam();        lbExams.DataSource = exam.DataLoad();        lbExams.DataTextField = "ExamName";        lbExams.DataValueField = "ExamNumber";        DataBind();     } } 
  6. Double-click the ListBox control and enter the following code in the ListBox 's SelectedIndexChanged event handler:

     private void lbExams_SelectedIndexChanged(      object sender, System.EventArgs e) {     lblSelected.DataBind(); } 
  7. Run the project. The ListBox control displays the ExamName property of every object in the DataView . Note that the DataLoad() method has a return value typed as ICollection , which is one of the types the ListBox can use as a DataSource . When you select an exam name , the corresponding ExamNumber value appears in the Label control.

Understanding the previous example is crucial for the effective use of the DropDownList and ListBox controls in applications. Using these controls can be a little tricky because the ListBox control is bound to two different things. Here's a review of how it all fits together:

  • The ListBox control in the previous example draws the list of items to display from the DataView of exam information. The list portion of the list box is complex data bound to this object. The complex binding is managed by setting the DataSource , DataTextField , and DataValueField properties of the ListBox control.

  • When you first load the form, the data is loaded by calling the DataBind() method of the ListBox control itself. The check of the IsPostBack property of the page ensures that this happens only once. If you neglect to check, the data is loaded when the form is posted back and you lose the information on which the ListBox item was selected.

  • When you click an item in the ListBox control, it posts that information back to the server because the AutoPostBack property of the ListBox control is set to true .

  • The SelectedIndexChanged event handles binding the currently selected row of the ListBox control to the Label control. The code for this calls the DataBind() method of the Label control itself.

  • You can use the DataTextField and DataValueField properties of the ListBox control to cause it to show one value while binding another, as in the previous example.

Data binding works the same way for all the list controls, which means the code for data binding the CheckBoxList and RadioButtonList controls is similar.

Binding to a DataGrid Control

The DataGrid control is designed to let you see an entire collection of data (often called a result set ) at one time. The following example shows how to bind a DataView object to a DataGrid control:

  1. Add a new Visual C# ASP.NET Web Application project named Example6_2 to the solution.

  2. Copy the Exam.cs class from the Example6_1 project to the current project.

  3. Place a DataGrid control ( dgExams ) on the Web form. Double-click the Web form and add the following code in the Page_Load() event handler:

     private void Page_Load(object sender, System.EventArgs e) {     // Create an Exam class object and call the DataLoad()     method to assign it to the DataGrid's DataSource     Exam exam = new Exam();     dgExams.DataSource = exam.DataLoad();     dgExams.DataBind(); } 
  4. Run the project. The DataGrid control displays all the information from the exam's DataView object.

The DataGrid control is extremely configurable. Visual Studio .NET includes two interfaces for setting the display properties of a DataGrid control. First, you can set individual properties to control the look of the DataGrid control in the Properties window. Second, you can right-click the DataGrid control and select AutoFormat. This invokes the AutoFormat dialog box that helps in changing the appearance of a DataGrid control.

The DataBind() Method

DataBind() is a method of the Page object (which, of course, represents the entire ASP.NET Web form) and of all the server controls. Data-binding expressions are not evaluated until you explicitly call the DataBind() method. This gives you flexibility to decide when to bind things and lets you run preliminary code to calculate values, if necessary.

The DataBind() method cascades from parent controls to their children. If you call the DataBind() method of the Page , all the data-binding expressions on the page are evaluated. Additionally, if you call the DataBind() method of a control that has constituent controls, all the data-binding expressions in any of those controls are evaluated.

In addition to the design-time data-binding expressions you've already seen, you can perform runtime data binding by responding to the DataBinding event of a control, as shown in the following example. This event is raised by each control when its DataBind() method is invoked:

  1. Add a new Visual C# ASP.NET Web Application project named Example6_3 to the solution.

  2. Place a Label control ( lblRuntime ) on the Web form.

  3. Switch to Code view and add the following code to the Page_Load() event handler:

     private void Page_Load(object sender, System.EventArgs e) {     lblRuntime.DataBind(); } 
  4. Attach an event handler to the DataBinding event of the Label control and add the following code to the event handler:

     private void lblRuntime_DataBinding(object sender, System.EventArgs e) {     lblRuntime.Text = "Runtime data binding"; } 
  5. Set the project as the startup project for the solution and run the project. The user interface displays runtime data binding as the text of the Label control.

Using the Data Form Wizard

Visual Studio .NET offers a visual tool for automatic data binding: the Data Form Wizard. In the following example, you'll see how to use the wizard to quickly build a multiple-table form that displays data from the Customers and Orders tables in the Northwind sample database. Here's how:

  1. Add a new Visual C# Empty Web Project ( Example6_4 ) to the solution. Select Project, Add New Item. In the Add New Item dialog box, select the Data Form Wizard and click Open.

  2. Read the Welcome screen of the wizard and click Next. The next screen helps you choose a DataSet object to use with the data form. A DataSet object is a .NET Framework object that you can think of as representing one or more tables from a database. (It's actually more flexible than that, but that's enough for this example.) On this screen, choose to create a new DataSet object named dsCustOrders . Click Next.

  3. The next screen helps you choose or build a data connection. A data connection tells Visual C# .NET which database contains the data you want to retrieve. You haven't set up any data connections yet, so click the New Connection button. This opens the Data Link Properties dialog box.

  4. Click the Provider tab of the Data Link Properties dialog box and select Microsoft OLE DB Provider for SQL Server.

  5. Click the Connection tab of the Data Link Properties dialog box and enter the information you need to use the Northwind database, as shown in Figure 6.1.

    Figure 6.1. Use the Data Form Wizard to create a data connection to the Northwind sample database.

    graphics/06fig01.jpg

    graphics/note_icon.gif

    Whenever I use data from a database in this book, I use the Northwind sample database included with Microsoft .NET Framework Software Development Kit (SDK) QuickStart Samples. These samples use Microsoft Data Engine (MSDE), a stripped-down version of SQL Server. See the .NET Framework SDK readme file for information on installing MSDE. You can also download MSDE from www.asp.net/msde.


  6. Click OK on the Data Link Properties dialog box to create the connection and return to the Data Form Wizard. Select the new connection in the combo box (it should have a name such as MACHINENAME .Northwind.dbo ) and click Next.

  7. On the Choose Tables or Views screen, select the Customers and the Orders table. Click Next.

  8. The next screen helps you specify the relationship between the two tables, Customers and Orders. Name the new relationship relCustOrders . Then select Customers as the parent table, select Orders as the child table, and select CustomerID as the key field in each table. Figure 6.2 shows the wizard at this point. Click the > button to create the new relationship; then click Next.

    Figure 6.2. When you use the Data Form Wizard to create a relationship between tables, it automatically generates code to keep the tables synchronized.

    graphics/06fig02.jpg

  9. On the Choose Tables and Columns to Display on the Form screen, leave all the columns in both tables selected; then click Finish.

  10. Set Example6_4 as the startup project and set DataForm1 as the start page for the project. Run the project to experiment with the data form.

The data form initially opens with only a Load button visible. Clicking the button loads all the rows from the Customers table. Each row has a Show Details link in the first column, and clicking this link loads the orders for that customer. The form knows which orders go with which customer thanks to the relationship you created between the two tables (see Figure 6.3).

Figure 6.3. A two-table data form that uses one DataGrid control for each table and uses code to keep the two DataGrid controls synchronized.

graphics/06fig03.jpg



MCAD Developing and Implementing Web Applications with Visual C#. NET and Visual Studio. NET (Exam [... ]am 2)
MCAD Developing and Implementing Web Applications with Visual C#. NET and Visual Studio. NET (Exam [... ]am 2)
ISBN: 789729016
EAN: N/A
Year: 2005
Pages: 191

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net