Export (0) Print
Expand All

Walkthrough: Creating a Web User Control

Web user controls are controls that you can define as you need them for your applications, using the same programming techniques that you use to write Web Forms pages. You can create Web user controls when you need to create reusable pieces of UI that will be used throughout your application. A user control can contain HTML, server controls, and event-handling logic. Like a compiled control, it can expose properties that the host Web Forms page can set.

Note   Web user controls are not to be confused with Web custom controls. For more information, see Recommendations for Web User Controls vs. Web Custom Controls.

The steps to create a user control are very similar to those for creating a Web Forms page. You design the UI visually by arranging ASP.NET server controls, HTML, and static text on the design surface, binding to data, and writing code to handle events raised by the controls. Like a Web Forms page, a user control can handle page processing events, such as Page_Load.

This walkthrough creates a menu selection control that passes the selected item back to the page in the URL query string. This style of navigation is useful when your application uses a single page to display a particular kind of data, but you also want to provide a filtered view of the data. For example, you might have a Sales page showing data that can be filtered by region. A user can navigate directly to the data he wishes to see by clicking a button that puts the filter in the URL as a query-string element, as in this example that limits the information displayed to sales in the northeast region:

http://sales/salesreport.aspx?region=northeast

In this walkthrough, you will create a control that displays information categories as a menu on a Web Forms page. It gets the categories and populates the menu dynamically from a data source on the page, in this case a string array. When a menu item is clicked, that menu item's index number in the array is added as a parameter to a URL. That URL is passed to the host page, which takes the parameter and displays the information that is associated with that index number in a Label control; in this case, the information is simply the category name from the same string array.

You will do the following steps to create the user control:

  • Open a new user control in the designer
  • Set a databinding expression for the user control
  • Expose the data source and selection as properties to a Web Forms page
  • Initialize the user control

You will also do the following to use the control on a Web Forms page:

  • Add the user control to a page
  • Create a data source for the user control
  • Set the user control's properties
  • Provide a filter presentation in the Web Forms page, based on the user control's selection
  • Run the Web Forms page to test the control

When you finish, your page should look something like this:

3457w616.vbwebusercontrol(en-us,VS.71).gif

Creating the User Control

The first step is to start a new project and add a Web user control to it.

To create the Web user control

  1. On the File menu, point to New, and then click Project.

    The New Project dialog box appears.

  2. In the Project Types pane, choose Visual Basic Projects or Visual C# Projects. In the Templates pane, select ASP.NET Web Application and click OK.

    A new project will be created with the default name at the default location.

  3. Close the newly-created .aspx file. You won't need it in this walkthrough.
  4. On the Project menu, click Add Web User Control.

    The Add New Item dialog box appears, with Web User Control selected.

  5. Type menu.ascx in the Name box, and click Open. The user control opens in the designer.

To display the data in your user control, add a DataList control to the design surface. The DataList control takes each item from a data source, formats it and the entire data list according to the properties you specify, and displays the list of items. Because the list is dynamically generated based on the data source, this control is easily reusable.

To add the DataList control and set its properties

  1. From the Web Forms tab of the Toolbox, add a DataList control to the menu.ascx page.

    This control will populate the menu by displaying a list of available options, which it will get from an array that is created in the host Web Forms page. To make the items appear on the page in the menu format "Item1 | Item2 | Item3", the DataList control display properties must be set correctly.

  2. Make sure the DataList control is selected, and click Property Builder at the bottom of the Properties window to open the DataList1 Properties dialog box.
  3. On the General page, in the Repeat layout group, set Direction to Horizontal.
  4. On the Format page, in the Objects list, expand the Items node and select Selected Items. In the Appearance group, select Bold, and then click OK.

    This setting will make the menu item that is selected appear in bold letters.

  5. Right-click the DataList control to show the shortcut menu, and then point to Edit Template and click Separator Template.
  6. Position the insertion point in the blank row of the Separator template and type the "|" character.

    This character will be used to separate the menu items when they are listed.

Each data item that appears in the DataList menu will have an array index value, with a lower bound of 0. You will use this number to request the information associated with that menu item, by adding it as a parameter to the URL that is passed to the host page. To generate the URL, format the data items as hyperlinks using the HyperLink control, and bind that control to the data source. You can then design a binding expression that dynamically generates the appropriate request string for each hyperlink.

To add a HyperLink control and set the binding expression

  1. Right-click the DataList control, and then point to Edit Template and click Item Templates. Several more template fields appear in the DataList control.

    The user needs to be able to click a menu item to retrieve the data related to that menu item. Therefore, each item needs to be a hyperlink.

  2. From the Web Forms tab of the Toolbox, drag a HyperLink control to the blank row in the DataList control beneath the heading ItemTemplate.
  3. Make sure that the HyperLink control is selected, and then select (DataBindings) in the Properties window and click the ellipsis button in the value field.

    The DataBindings dialog box appears. The Text property is selected by default in the Bindable Properties list.

  4. In the Binding for Text group, under Simple binding, expand the Container node and select DataItem.

    This will bind the Text property of each hyperlink to the data item of the container, which in this case is the DataList control. The DataList control will receive its data items from the array that is created in the host Web Forms page.

  5. In the Bindable Properties list, select the NavigateUrl property.
    Note   When you click the NavigateUrl property, the icon next to the Text property changes to show that it is data-bound.
  6. In the Binding for NavigateUrl group, under Simple binding, select ItemIndex.

    This is the index number of the data item in the array. To append this number correctly to the URL so that the URL retrieves the data item at that index number, you must format it as a parameter. Name the parameter "category".

    Security Note   The URL associated with a hyperlink can be tampered with by a malicious user. For more information, see Scripting Exploits.
  7. In the Format box, enter this string (note the curly braces around the 0):
    ?category={0} 
    

    Now you must complete the URL so that it points to the host Web Forms page.

  8. Click Custom binding expression and add this code to the beginning of your almost-complete databinding expression:
    Request.Path + 
    

    Your complete custom databinding expression should be:

    Request.Path + DataBinder.Eval(Container, "ItemIndex", "?category={0}")
    
  9. Click OK to close the DataBindings dialog box.

The databinding expression that you entered contains the syntax for building a URL at run time, based on information from the link associated with the array number.

When the user control runs, this expression is evaluated as follows:

  • First, Request.Path is replaced by the name of the current page. This approach lets you use your menu control on any page, regardless of what it is named. For more information, see HttpRequest.Path Property.
  • Next, the DataBinder.Eval method takes the item's index number, and substitutes it for the "{0}" token in the format string. For more information, see DataBinder.Eval Method.

For example, if the hosting page is called MyPage.aspx, and the index for this item is 1, the generated URL would be:

MyPage.aspx?category=1

Exposing Properties to the Web Forms Page

You can bind a DataList control to a number of different types of data sources. For the sake of simplicity, this walkthrough binds the DataList control to a simple string array, which is passed from the Web Forms page to the user control via a property exposed by the user control.

To declare the array and selection properties

  1. Press F7 to switch from Design view to the code-behind file.
  2. Add a public, class-level declaration for a string array, and name it values.

    This array will hold the list of data items.

  3. Similarly, declare selection as Integer and initialize it to -1.

    This variable will hold the index value for the menu item that the user selects. Since -1 is not an index value in the array, the variable will not be assigned an index value on initialization.

    The top section of your code should look something like this:

    ' Visual Basic
    Public MustInherit Class menu
       Inherits System.Web.UI.UserControl
       Protected WithEvents DataList1 As System.Web.UI.WebControls.DataList
       Public values() As String
       Public selection As Integer = -1
    
    // C#
    public abstract class menu : System.Web.UI.UserControl
    {
       protected System.Web.UI.WebControls.DataList DataList1;
       public string[] values;
       public int selection = -1;
    

Initializing the Control

Now that the pathways and formats are established, you need to add the code to initialize the connection between the control and the data. Use the page load event to do this initialization.

  1. In the Page_Load procedure, set values to be the DataSource property for the DataList control.
  2. Set selection to be the SelectedIndex property for the DataList control.
  3. Call the DataBind() method of the DataList control to create the DataList items.

    Your Page_Load procedure will look like this:

    ' Visual Basic
    Private Sub Page_Load(ByVal sender As System.Object, _
          ByVal e As System.EventArgs) Handles MyBase.Load
       DataList1.DataSource = values
       DataList1.SelectedIndex = selection
       DataList1.DataBind()
    End Sub
    
    // C#
    private void Page_Load(object sender, System.EventArgs e)
    {
       DataList1.DataSource = values;
       DataList1.SelectedIndex = selection;
       DataList1.DataBind();
    }
    
  4. Save and close the control.

Consuming the User Control

Now that you have created a user control, you will actually use it in a Web Forms page. It is possible to use your control on multiple pages and bind it to different data on each page. In this walkthrough, however, you consume the user control on a single page called MyPage.aspx.

To add the user control to a Web Forms page

  1. On the Project menu, click Add Web Form.

    The Add New Item dialog box appears with Web Form selected.

  2. Change the Name to MyPage.aspx, and click Open.

    The new Web Forms page opens in Design view.

  3. Select the menu.ascx file in Solution Explorer and drag it onto your page. It will appear as a user control, with the ID Menu1.

    The user control will be displayed on the page as a tag showing its type and name; there is no graphical display for user controls within a page since this type of control is not fully compiled until you run the page.

    User Control Glyph on a Web Forms Page

    3457w616.vbusercontrolglyph(en-us,VS.71).gif

  4. From the Web Forms tab of the Toolbox, add a Label control to the page.

    This control is used to display the information associated with the selected menu item.

  5. Save your files.

Since Visual Studio does not automatically add a declaration of user controls to the code, the next step is to add the declaration manually.

To add a code-behind declaration for the user control

  1. Press F7 to switch from Design view to the code-behind file.
  2. In the Declarations area, add a line to declare the user control Menu1 as menu.
    ' Visual Basic
    Public Class MyPage
       Inherits System.Web.UI.Page
       Protected WithEvents Label1 As System.Web.UI.WebControls.Label
       Protected Menu1 As menu
    
    // C#
    public class MyPage : System.Web.UI.Page
    {
       protected System.Web.UI.WebControls.Label Label1;
       protected menu Menu1;
    

Now that you have a code declaration for the user control, you must set its properties programmatically.

To create a data source for the user control

  1. In the Page_Load method of the Web Forms page, declare a string array and name it values. This is the array that will be called by the user control that you created. Populate the array with three items: "News", "Events", and "Reference".
  2. Assign the array to the values property of the Menu1 user control.

    Your code should look like this:

    ' Visual Basic    
    ' set datasource for menu
    Dim values() As String = New String() {"News", "Events", "Reference"}
    Menu1.values = values
    
    // C#
    //set datasource for menu
    String[] values = new String[]{"News", "Events", "Reference"};
    Menu1.values = values;
    

To find out which item in the menu is selected, check the "category" parameter that you set when you created the custom binding expression for the Hyperlink control.

To capture the user control selection

  1. In the Page_Load method, add a line of code to copy the current selection (if any) from the URL query string:
    ' Visual Basic
    Dim selectionId As String = Request.Params("category")
    
    // C#
    String selectionId = Request.Params["category"];
    
    Security Note   Information passed in a query string can be tampered with by a malicious user. Do not rely on query strings to convey important or sensitive data. For more information, see Scripting Exploits.
  2. If the selection was set, pass it on to the user control via the control's selection property and set the text of the Label control to indicate the current selection. The Web Forms page can use the selection information to filter the view it displays.
    ' Visual Basic
    If (selectionId <> "") Then
       Dim SelectIndex As Integer = CInt(selectionId)
       Menu1.selection = SelectIndex
       Label1.Text = "Current selection is: " & values(SelectIndex)
    End If
    
    // C#
    if(selectionId != "")
       {
          int SelectIndex = Convert.ToInt16(selectionId);
          Menu1.selection = SelectIndex;
          Label1.Text = "Current selection is: " + values[SelectIndex];
       }
    

    That completes the Web Forms page. Your entire Page_Load procedure should look like this:

    ' Visual Basic
    Dim values() As String = New String() {"news", "events", "reference"}
    Menu1.values = values
    Dim selectionId As String = Request.Params("category")
    If (selectionId <> "") Then
       Dim SelectIndex As Integer = CInt(selectionId)
       Menu1.selection = SelectIndex
       Label1.Text = "Current selection is: " & values(SelectIndex)
    End If
    
    // C#
    String[] values = new String[]{"News", "Events", "Reference"};
    Menu1.values = values;
    String selectionId = Request.Params["category"];
    if(selectionId != "")
       {
          int SelectIndex = Convert.ToInt16(selectionId);
          Menu1.selection = SelectIndex;
          Label1.Text = "Current selection is: " + values[SelectIndex];
       }
    
  3. Save and close the page.

Testing the Web Forms Page

You can now test your page to see the functionality of the menu.

To test the Web Forms page

  1. Right-click MyPage.aspx in Solution Explorer and choose Set As Start Page on the shortcut menu.
  2. Press F5 to run MyPage.aspx and test the user control. Click each of the menu selections to test their functionality.

The user control displays each string that is passed from the array in the Web Forms page as a separate link. You set the DataSource property of the DataList control to the array and use the DataList to render a hyperlink for each of the items in the DataSource property. The DataList control also takes care of applying a different visual style to the selected link.

See Also

Developing ASP.NET Server Controls | Web Control Library Template | Recommendations for Web User Controls vs. Web Custom Controls | Introduction to Web User Controls | Walkthrough: Converting a Web Forms Page to a User Control | Overview of Web Application Security Threats

Show:
© 2014 Microsoft