16.7 Databinding Web Controls

 <  Day Day Up  >  

You want to extract the values for a server-side control from a database.


Technique

The ultimate goal of databinding an ASP.NET control is to get to the point where you can associate a DataSet with the control itself. How you ultimately do it is up to you because you can take several different avenues to wind up with this goal. Chapter 14 demonstrated how to work with databases to create DataSet objects and fill them by using a DataAdapter . This recipe presents two techniques for databinding a Web control. Each method results in the same solution but goes about it using two different methods .

The first method for databinding a Web control uses the techniques explained in Chapter 14. In other words, you write code to create a database connection, construct an adapter, and finally fill a DataSet that will be bound to the control. This example and the examples later in this chapter regarding data-bound controls use the Northwind database through a SqlConnection object.

To bind a control, create a data connection to the database you plan to use. This example creates a SqlConnection object by passing the connection string to the SqlConnection constructor to connect to the Northwind database:

 
 private void Page_Load(object sender, System.EventArgs e) {     string connectionString = "Data Source=localhost;Integrated      Security=SSPI;Initial Catalog=northwind";     // create database connection     SqlConnection sqlConn = new SqlConnection( connectionString ); 

The next step is to create a DataAdapter , which in this case is a SqlDataAdapter . The first parameter of the constructor is the SELECT command specifying the rows to extract from a table. In the following example, the SELECT command returns all rows from the table named Products . The second parameter to the constructor is the database connection object created earlier:

 
 // create a data adapter passing the SELECT statement SqlDataAdapter nwDA = new SqlDataAdapter( "SELECT * FROM PRODUCTS", sqlConn ); 

After you create the database connection and data adapter, you are ready to extract the data into a DataSet . To do so, create a new DataSet and call the Fill method defined in the DataAdapter , passing the DataSet to fill as the parameter:

 
 // create dataset to fill DataSet nwDS = new DataSet(); // fill dataset nwDA.Fill( nwDS ); 

At this point, the DataSet contains the data that you want to bind to the control. In the examples shown, the DataSet contains each row from the Products table of the Northwind database. To bind this data to a control, set the DataSource equal to the DataSet object that you created. To specify the text to use for each option within the control, set the DataTextField property equal to the column name of the data table. You can also specify a DataValueField that represents the actual value of each option of a control (each item in a drop-down list, for example). You would also use a column name from the data table. In the following code, a drop-down list is bound to the DataSet created in this recipe. The text for each item in the list represents the values from the ProductName column, and each item value is the corresponding ProductID . Finally, to populate the drop-down list, call the DataBind method defined in the Page class:

 
 // bind control     ddlCode.DataSource = nwDS;     ddlCode.DataTextField = "ProductName";     ddlCode.DataValueField = "ProductID";     // databind will populate both controls     DataBind(); } 

The method just shown demonstrates how to databind a control programmatically. Another method is to let the Web Form designer generate the code for you. Just as with the previous data-binding method, there are advantages and disadvantages, which are explained in the corresponding comments for this recipe.

Assuming that you have created the necessary controls for the Web Form, you are now ready to bind the necessary controls. Within the designer, open the Server Explorer, which by default is docked to the left side of the IDE. Expand the Servers tree and select the Products table from the Northwind SQL database, as shown in Figure 16.1. To create the SqlConnection and SqlDataAdapter objects, drag and drop the Products table from Server Explorer onto the Web Form. To create the DataSet object, select the SqlDataAdapter that was created within the form and click on the Generate Dataset verb located at the bottom of the Property Browser. When the Generate Dataset dialog appears, you can accept the defaults or change the name of the DataSet to something more meaningful.

Figure 16.1. The Northwind database in Server Explorer.

graphics/16fig01.gif

At this point, the database connection object has been created as well as the data adapter and a specialized DataSet object. To bind the data to a control, select the control within the Web Form designer and set the DataSource property to the DataSet . The Property Browser can determine the available data sets, which means you can simply select the correct object from a drop-down list. Next, select the column name that will be used for each item's text by accessing the DataTextField property. Likewise, set the column name that is used for each item's value by selecting the correct column name in the DataValueField property.

Although the Web Form designer generates a lot of code for databinding controls, you still have to add the code to fill the DataSet and bind the resultant data to a control. Open the code-behind file. In the Page_Load method, fill the DataSet by calling the Fill method defined in the generated SqlDataAdapter object. Finally, call the DataBind method to populate the data-bound controls:

 
 private void Page_Load(object sender, System.EventArgs e) {     // fill dataset for designer bound control     sqlDataAdapter1.Fill( productsDS1 );     // databind controls     DataBind(); } 

Comments

What was just shown represents two different ways of binding data from a database to a Web Form control. Neither one is better than the other, but each has its advantages and disadvantages that you must consider. You can programmatically databind a control with just a few lines of code to create the database connection, create an adapter, and fill a DataSet with the adapter. As you can see from the example, the code is easily manageable because it all resides within the same method. This method is well suited for read-only controls that simply display data from a database. However, once you start adding the necessary code to insert, delete, and update tables within the database while still maintaining the databinding code, the complexity begins to rise.

Using the designer to databind a control is also a fairly trivial matter once you understand the necessary steps. However, for controls that simply serve to display data, the amount of generated code that the designer provides might be overkill. After creating the necessary data binding with a control, expand the hidden region within the code-behind code, and assuming you accepted the defaults when generating the DataSet , you see a lot of lines of code related to such things as the insert, delete, update, and select commands as well as the code that associates the necessary data objects with each other. For anything but the simplest control, however, the generated code saves a lot of time and possibly eliminates simple mistakes that can occur if you write the code yourself. Additionally, the customized DataSet object that is created also contains helper methods that allow you to easily perform various operations on the data without having to use SQL commands because they have also been automatically generated. For example, to insert a new row into the Products table of the Northwind database using the objects that were created by the designer, the code appears as follows :

 
 productsDS1.Products.AddProductsRow( "New Product", 1, 1, "1", 1.00m, 0,  10, 1, false ); sqlDataAdapter1.Update( productsDS1 ); 
 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

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