Programming ASP.NET: Custom and User Controls, Part 1
Pages: 1, 2, 3, 4
Adding Code
So far, all you've put into the user control is straight HTML. This is simple, but also somewhat limited. There is no reason to so severely limit the user control. In the next example, you'll add support for filling the list box with books from a database. To do so, you'll need to add a table to the ProgASPNetBugs database, as shown in Figure 14-2.
|
|
You'll also need to populate this table with the values shown in Figure 14-3, or simply download the entire database with data already provided.
|
|
You are ready to fill the list box dynamically, using data binding. Strip out all the code that fills the list box by hand. This reduces Example 14-3 to two lines:
<ASP:DropDownList id=ddlBooks runat=server></ASP:DropDownList>
The key to making this work is now in the Control tag:
<%@ Control Language="c#" AutoEventWireup="false"Codebehind="BookList.ascx.cs"Inherits="UserControl1.WebUserControl1"%>
The Codebehind attribute points to the code-behind page. In that page, you'll add code to the Page_Load method to bind the list box to the appropriate table in the database. That code is shown in Example 14-4 for C# and Example 14-5 for VB.NET.
Example 14-4: C# Page_Load from the code-behind page for the user control
private void Page_Load(object sender, System.EventArgs e){if (!IsPostBack){string connectionString ="server= " + ServerName +"; uid=sa;pwd=" +Password + "; database= " + DB;// get records from the Bugs tablestring commandString ="Select BookName from Books";// create the data set command object// and the DataSetSqlDataAdapter dataAdapter =new SqlDataAdapter(commandString, connectionString);DataSet dataSet = new DataSet( );// fill the data set objectdataAdapter.Fill(dataSet,"Bugs");// Get the one table from the DataSetDataTable dataTable = dataSet.Tables[0];ddlBooks.DataSource = dataTable.DefaultView;ddlBooks.DataTextField = "BookName";ddlBooks.DataBind( );}}
Example 14-5: VB.NET Page_Load from the code-behind page for the user control
Private Sub Page_Load(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles MyBase.LoadIf Not IsPostBack ThenDim connectionString As String = _"server= " & ServerName &"; uid=sa;pwd=" +Password + "; database= " + DB;' get records from the Bugs tableDim commandString As String = _"Select BookName from Books"' create the data set command object' and the DataSetDim dataAdapter as SqlDataAdapter = _new SqlDataAdapter( _commandString, connectionString);Dim dataSet As DataSet = New DataSet( )' fill the data set objectdataAdapter.Fill(dataSet, "Books")' Get the one table from the DataSetDim dataTable As DataTable = dataSet.Tables(0)ddlBooks.DataSource = dataTable.DefaultViewddlBooks.DataTextField = "BookName"ddlBooks.DataBind( )End IfEnd Sub
The host page does not change at all. The updated user control now works as intended, loading the list of books from the database, as shown in Figure 14-4.

