Finding a Control Inside a Template
Sometimes it is necessary to locate a control contained inside a template. If a control is given an ID in a template, that control can be
retrieved from its container (the first control in the parent hierarchy that supports INamingContainer). In this case, the
container is the DataListItem control. Note that even though there are several controls with the same ID (by virtue of the DataList's
repetition), each is contained logically in the namespace of the DataListItem container control.
You can go through the DataList's Items collection to retrieve the DataListItem for a given index, and then call
the DataListItem's FindControl method (inherited from the base Control class) to retrieve a control with a particular ID.
<script runat="server">
Public Sub Page_Load(sender As Object, E As EventArgs))
' set datasource and call databind here
For I=0 To MyDataList.Items.Count-1
Dim IsChecked As String = MyDataList.Items(i).FindControl("Save").Checked.ToString()
If IsChecked = "True" Then
...
End If
Next
End Sub
</script>
<ASP:DataList id="MyDataList" runat="server">
<ItemTemplate>
<asp:CheckBox id="Save" runat="server"/> <b>Save to Favorites</b>
</ItemTemplate>
</ASP:DataList>
VB
The following sample demonstrates this code in action.
- The DataList and Repeater controls provide developers fine-tuned control over the rendering of data-bound lists.
- Rendering of bound data is controlled using a template, such as the HeaderTemplate, FooterTemplate, or ItemTemplate.
- The Repeater control is a general-purpose iterator, and does not insert anything in its rendering that is not contained in a template.
- The DataList control offers more control over the layout and style of items, and outputs its own rendering code for formatting.
- The DataList supports the Select, Edit/Update/Cancel, and Item Command events, which can be handled at the page level by
wiring event handlers to the DataList's Command events.
- DataList supports a SelectedItemTemplate and EditItemTemplate for control over the rendering of a selected or editable item.
- Controls can be programmatically retrieved from a template using the Control.FindControl method. This should be called on
a DataListItem retrieved from the DataList's Items collection.
Copyright 2001-2002 Microsoft Corporation. All rights reserved.