Export (0) Print
Expand All

Allowing Users to Select Items in a DataList Web Server Control

Visual Studio .NET 2003

You can specify that users can select individual items in the DataList Web server control. Typically, selecting an item highlights it visually. In addition, you might display different information for a selected item.

To allow users to select items in a DataList control

  1. Set the control's SelectedItemStyle properties. For details, see Customizing the Appearance of ASP.NET Server Controls Using Styles.
  2. Optionally, create a SelectedItemTemplate to display different text and controls for the selected item. For details, see Creating Web Server Control Templates.
  3. In the ItemTemplate (and AlternatingItemTemplate, if you are using it), add a Button or LinkButton Web server control.
  4. Set the CommandName property of the button from Step 3 to select (case-sensitive).
  5. If you have created a separate SelectedItemTemplate, you need to rebind the list upon selection. Create an event handler for the control's SelectedIndexChanged event. For details, see Creating Event Handlers in Web Forms Pages. In the event handler, call the control's DataBind method to refresh the information in the control. The complete code would look something like this:
    ' Visual Basic
    Private Sub DataList1_SelectedIndexChanged( _
    ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles DataList1.SelectedIndexChanged
       DataList1.DataBind()
    End Sub
    
    // C#
    private void DataList1_SelectedIndexChanged (object sender, System.EventArgs e)
    {
       DataList1.DataBind();
    }
    
  6. To cancel the selection, set the control's SelectedIndex property to -1. To accomplish this, you could add a Button Web server control to the SelectedItem template and set its CommandName property to unselect. The Click event for this button would also be bubbled to the DataGrid control's ItemCommand event. The complete code might look something like the following:
    ' Visual Basic
    Private Sub DataList1_ItemCommand(ByVal source As Object, _
    ByVal e As System.Web.UI.WebControls.DataListCommandEventArgs) _
    Handles DataList1.ItemCommand
       If e.CommandName = "unselect" Then
          DataList1.SelectedIndex = -1
       End If
       DataList1.DataBind()
    End Sub
    
    // C#
    private void DataList1_ItemCommand(object source, System.Web.UI.WebControls.DataListCommandEventArgs e)
    {
       if (e.CommandName == "unselect")
       {
          DataList1.SelectedIndex = -1;
       }
       DataList1.DataBind();
    }
    

See Also

Introduction to the DataList Web Server Control | Allowing Users to Delete Items in a DataList Web Server Control | Allowing Users to Edit Items in a DataList Web Server Control | Creating Event Handlers in Web Forms Pages | Responding to Button Events in DataList, Repeater, or DataGrid Items

Show:
© 2014 Microsoft