Creating More Complex User Controls

In the previous two examples, you created simple user controls that merely expose user interface elements. Neither user control required you to write any code, nor did either provide any interactive functionality.

What if you want to encapsulate often-needed functionality as well? For example, in previous chapters on more than one occasion, you filled a DropDownList control with data. You used a SQL string with two columns, filled a DataReader or DataSet, and then either looped through the data or bound the control to the data. If you need to do this same thing often, it's a candidate for creating a user control.

Your new control, the DataDropDownList control, will contain a standard DropDownList control and will provide the members shown in Table 21.2. You'll set the DataTable, DataTextField, and DataValueField properties; then you'll call the DataBind method to fill the control with its data. If you set the AutoPostBack property to True, you'll get an immediate postback when you select an item from the list. You can react to the control's SelectedIndexChanged event, and in your event procedure, you can retrieve the SelectedItem property from the control.

Table 21.2. The New User Control Supplies These Members
Member Type Description
AutoPostBack Property (Boolean) Exposes the DropDownList control's AutoPostBack property
DataBind Method Overrides the DropDownList control's DataBind method, effectively retrieving the data and calling the control's DataBind method
DataTable Property (String) Determines the table from Northwind supplying the data
DataTextField Property (String) Exposes the DropDownList control's DataTextField property
DataValueField Property (String) Exposes the DropDownList control's DataValueField property
SelectedIndexChanged Event Raised when the DropDownList control's SelectedIndexChange event occurs
SelectedItem Property (ListItem) Exposes the DropDownList control's SelectedItem property

The following sections walk you through creating your own DataDropDownList control.

First, follow these steps to get started:

1.
Select the Project, Add Web User Control menu item. Name the new control DataDropDownList.ascx.

2.
On the control's designer, add a DropDownList control. Set the new control's ID property to ddlList.

3.
Use the View, Code menu item to view the code for the control and add a declaration for mstrDataTable immediately above the Page_Load procedure:

Private mstrDataTable As String

You'll use this member variable to maintain the name of the table that provides the data for the DropDownList control.

Creating Properties

Next, add the DataTable, DataTextField, and DataValueField property procedures for your control, as shown in Listing 21.1.

Listing 21.1. Add Property Procedures to Your Control
Public Property DataTable() As String
  Get
    Return mstrDataTable
  End Get
  Set(ByVal Value As String)
    mstrDataTable = Value
  End Set
End Property

Public Property DataTextField() As String
  Get
    Return ddlList.DataTextField
  End Get
  Set(ByVal Value As String)
    ddlList.DataTextField = Value
  End Set
End Property

Public Property DataValueField() As String
  Get
    Return ddlList.DataValueField
  End Get
  Set(ByVal Value As String)
    ddlList.DataValueField = Value
  End Set
End Property

TIP

If you look carefully, you'll see that the DataTextField and DataValueField properties simply get and set the corresponding properties of the DropDownList control contained within this user control. The DataTable property doesn't correspond to any property of the DropDownList control, so it requires a private variable in which to maintain its value.


Overriding the DataBind Method

Because you want your DataDropDownList control to behave as much like a standard DropDownList control as possible, you'll want to expose the same types of methods and properties as the standard control. With that in mind, your control should provide a DataBind method (a procedure that retrieves the data and hooks it up to the control). Because your control is inheriting from the base UserControl type, which provides its own DataBind method (this method doesn't actually do anything—you have to override it to provide the functionality), your DataBind procedure must use the Overrides keyword, indicating that it is overriding the base classes' implementation of the method.

Add this procedure to your class:

Public Overrides Sub DataBind()
  Dim strSQL As String
  Dim strConn As String

  strSQL = String.Format("SELECT {0}, {1} FROM {2}", _
   DataTextField, DataValueField, DataTable)
  strConn = Session("ConnectString").ToString

  With ddlList
    .DataSource = DataHandler.GetDataSet(strSQL, strConn)
    .DataBind()
  End With
End Sub

TIP

The DataBind method needs to retrieve values that are properties of the DataDropDownList control. When the code refers to the DataTextField property, for example, it's using the value of the property defined for the current instance of the class—the control whose code is currently running.


Rather than writing this same code for each DropDownList control you use, you can now simply add a DataDropDownList control to a page, set some properties, and get the functionality you need—all without having to worry about data retrieval each time you want to fill a DropDownList control.

Using the Control

In this section, you'll create a simple page to test out your DataDropDownList control. Follow these steps:

1.
Select the Project, Add Web Form menu item to add a new page. Name the new page DataDropDownListTest.aspx.

2.
From the Solution Explorer window, drag an instance of the DataDropDownList.ascx user control onto your new page. Set the name of the new control to dddlCategories.

3.
Add a Label control immediately below the user control. Set the Label control's ID property to lblCategory and delete its Text property.

4.
Double-click the page to display the code-behind file.

5.
Although Visual Studio normally adds a member variable corresponding to each control you place on the page so that you can program against the control, it doesn't do this for user controls. You'll need to modify the class file so that it looks like this, so you can program against the new user control:

Public Class DataDropDownListTest
  Inherits System.Web.UI.Page

  Protected WithEvents dddlCategories As DataDropDownList

6.
Modify the Page_Load procedure so that it looks like this, setting up the DataDropDownList control to display its data:

Private Sub Page_Load( _
 ByVal sender As System.Object, _
 ByVal e As System.EventArgs) _
 Handles MyBase.Load

  If Not Page.IsPostBack Then
    With dddlCategories
      .DataTable = "Categories"
      .DataTextField = "CategoryName"
      .DataValueField = "CategoryID"
      .DataBind()
    End With
  End If
End Sub

That's all it takes to load up the DataDropDownList control with data from the Categories table, and it's a lot less code than you'd otherwise have to write.

To test out your new page, right-click DataDropDownListTest.aspx in the Solution Explorer window and then select Build and Browse from the context menu. Your new user control should contain a list of categories from the Categories table.


Under the Hood

What actually happens when you drag a user control onto a page? Visual Studio .NET adds a Register directive to the HTML content of your page, looking something like this:

<%@ Register TagPrefix="uc1" TagName="DataDropDownList"
Src="DataDropDownList.ascx" %>

This directive includes three attributes:

  • TagPrefix (uc1 by default). Provides a unique tag name for your control. In the HTML for the page, you'll find uc1:DataDropDownList as the full control tag name. You can change this item, if you like, when you drop the first instance of the control on the page. You'll need to fix up any existing control instances to match once you modify this value.

  • TagName (DataDropDownList). Provides the control tag name. By default, this matches the name portion of the file containing the control. You can change this value, but you must change any existing elements within the page's HTML to match.

  • Src (DataDropDownList.ascx). Provides the file containing your user control. Don't change this or else the page won't be able to find the content for your control.

Dragging the control onto the page added the following HTML representing the control to the page's content:

<uc1:datadropdownlist
 id="dddlCategories" runat="server">
</uc1:datadropdownlist>

If you know the properties you want to set, at design time, you can also set those properties here in the control's element. For example, instead of writing the code you had added previously, you could modify this tag to contain the information, like this:

<uc1:DataDropDownList id="dddlCategories"
 DataTextField="CategoryName" DataValueField="CategoryID"
							DataTable="Categories" runat="server">
</uc1:DataDropDownList>

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.152.58