0

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");
4

3 回答 3

1

想...你得到了那个错误,因为列表视图还没有绑定,所以我认为最好的方法是在 ItemDataBound 事件上完成所有这些。您会发现下拉列表如下:

protected void FillDropdownlist(object sender, ListViewItemEventArgs e)
    {

     if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            DropDownList dr = (DropDownList)e.Item.FindControl("DaysDropDownList");
            FileUpload fl = (FileUpload)e.Item.FindControl("FileUpload");

            if (dr!= null)
            {
                //code here
            }
        }
}
于 2012-07-09T12:23:55.293 回答
0

那是因为MyListView.Controls[0]指向不包含这两个的内部控件。

尝试调试并准确找到您的容器控件,然后直接访问它而无需硬编码索引。可以通过行绑定调用的事件参数访问它。

我还可以建议您使用as运算符,因为它不会引发异常:

as 运算符类似于强制转换,只是它在转换失败时产生 null 而不是引发异常

IE

DropDownList dr = e.Item.FindControl("DaysDropDownList") as DropDownList;
FileUpload fl = e.Item.FindControl("FileUpload") as FileUpload;

或绑定后

//Loop i for the items of your listview
DropDownList dr = MyListView.Items[i].FindControl("DaysDropDownList") as DropDownList;
FileUpload fl = MyListView.Items[i].FindControl("FileUpload") as FileUpload;
于 2012-07-09T12:19:08.863 回答
0

您需要遍历Items列表视图的集合,然后FindControl在每个项目上使用。这样的事情应该让你走上正确的轨道:

foreach (var lvItem in MyListView.Items)
{
    if (lvItem.ItemType == ListViewItemType.DataItem)
     {
        DropDownList dr = (DropDownList)lvItem.FindControl("DaysDropDownList");
        FileUpload fl = (FileUpload)lvItem.FindControl("FileUpload");
    }
}
于 2012-07-09T12:25:00.490 回答