I’ve been playing around with the ListView control recently and am quite impressed with it. I like how it gives full control over the markup used as apposed to the other data driven controls.
I came across an issue where in my ItemTemplate I have a CheckBoxList which I needed to reference when I hit a button also in the ItemTemplate.
As the ItemTemplate repeats there will be many CheckBoxLists so how do I find the correct one?
The answer I found was in the ListView’s Items collection. On my button I set the CommandArgument to the DataItemIndex, then in my handler for the ListView’s ItemCommand event I used FindControl on the item matching the index.
Here is my item template:
<ItemTemplate>
   <div>
       <asp:Literal ID="lblForename" Text='<%# Eval("Forename") %>' runat="server" />
       <asp:Literal ID="lblSurname" Text='<%# Eval("Surname") %>' runat="server" />
      �
       <div>
           <asp:CheckBoxList  ID="cblRoles"
                               DataSourceID="odsRole"
                               DataValueField="ID"
                               DataTextField="Name"
                               OnDataBound="cblRoles_OnDataBound"
                               runat="server">
           </asp:CheckBoxList>
       </div>
      �
       <div>
           <asp:Button ID="btnSaveRoles"
                       Text="Save Roles"
                       CommandName="SaveRoles"
                       CommandArgument='<%# Container.DataItemIndex %>'
                       runat="server" />
       </div>
   </div>
</ItemTemplate>
And here is my event handler:
protected void lvUser_ItemCommand(object sender, ListViewCommandEventArgs e)
{
   try
   {
       if (e.CommandName.Equals("SaveRoles"))
       {
           CheckBoxList cblRoles = lvUser.Items[Convert.ToInt32(e.CommandArgument)].FindControl("cblRoles") as CheckBoxList;
           //Other code
       }
   }
   catch (Exception ex)
   {
       lblMessage.Text = ex.Message;
   }
}
So I’m using the FindControl method on the ListViewDataItem in the position passed via the CommandArgument which gives me the correct control.



[...] Using FindControl for a control in the ItemTemplate of a ListView … – I’ve been playing around with the ListView control recently and am quite impressed with it. I like how it gives full control over the markup used as apposed. [...]