Search code examples
asp.netlistviewfindcontrol

ListView find dropdownlist in table


I have a list view with table inside and i need to get all dropdown lists and file upload controls, but find returns nothing. This is my code:

<asp:ListView runat="server" ID="MyListView" OnItemDataBound="FillDropDownList">
    <LayoutTemplate>
        <table border="0" cellpadding="2" cellspacing="0">
        <tr>
        <th>Wholesaler</th>
        <th>Import</th>
        <th>Period</th>
        <th>Upload Date</th>
        <th>Upload</th>
        </tr>
            <asp:PlaceHolder ID="itemPlaceholder" runat="server" />
    </table>
    </LayoutTemplate>
    <ItemTemplate>
    <tr class="row1">
        <td><%# DataBinder.Eval(Container.DataItem, "Wholesaler") %></td>
            <td><%# DataBinder.Eval(Container.DataItem, "Import")%></td>
        <td><%# DataBinder.Eval(Container.DataItem, "Period")%></td>
        <td><asp:DropDownList runat="server" ID="DaysDropDownList"></asp:DropDownList></td>
       <td><asp:FileUpload ID="FileUpload" runat="server" /></td>
    </tr>
    </ItemTemplate>
</asp:ListView>

DropDownList dr = (DropDownList)MyListView.Controls[0].FindControl("DaysDropDownList");
FileUpload fl = (FileUpload)MyListView.Controls[0].FindControl("FileUpload");

Solution

  • You need to iterate over the Items collection of the listview, and then use FindControl on each item. Something like this should put you on the right track:

    foreach (var lvItem in MyListView.Items)
    {
        if (lvItem.ItemType == ListViewItemType.DataItem)
         {
            DropDownList dr = (DropDownList)lvItem.FindControl("DaysDropDownList");
            FileUpload fl = (FileUpload)lvItem.FindControl("FileUpload");
        }
    }