Why is the ASP.NET Repeater.Items collection empty, when controls are on the screen?

冷暖自知 提交于 2020-01-05 04:39:21

问题


I have an ASP page with the following repeater:

<asp:Repeater runat="server" ID="RegionRepeater"
    DataSourceID="SqlDataSourceRegions" EnableViewState="true">
    <ItemTemplate>
        <tr>
            <td valign="top">
                <b><%#Eval("description")%></b>
                <asp:HiddenField runat="server" ID="RegionID"
                    Value='<%#Eval("region_id")%>'/>
            </td>
            <td>
                <asp:FileUpload ID="FileUpload" runat="server" Width="368px" />
            </td>
        </tr>
    </ItemTemplate>
</asp:Repeater>

(The repeater is inside a Wizard, inside a content pane).

The code behind is connected to the

protected void Wizard1_NextButtonClick(object sender, WizardNavigationEventArgs e)

event. There are two items on the screen (two rows inside the table). However, when the code tries to read those items, the Items collection is empty!

foreach(RepeaterItem region in RegionRepeater.Items)
{
    // Never runs - the RegionRepeater.Items.Count = 0
    FileUpload fileUpload = (FileUpload) region.FindControl("FileUpload");
    String regionID = ((HiddenField)region.FindControl("RegionID")).Value;
    ...

Why is the collection empty, when there are controls drawn on the screen?

Thanks a lot for any help; this is starting to drive me nuts.

(BTW: I tried adding/removing the EnableViewState="true" tag)


回答1:


Have you made sure the repeater has been rebound on the postback?

The ASP.NET Page Life Cycle means that on a postback, you will need to rebind controls like the repeater in order for event handlers to be able to see the data.




回答2:


Check if you have a Page.DataBind() in the page code behind. That makes your repeater to bind with empty data.




回答3:


Maybe you do the databinding every time you load the page, do you check that there is no postbacl before you do it ?




回答4:


I believe Items is only populated when bound. So you have to rebind your data on every page load. This is due to the statless environment of the web; it doesn't remember the data source, but loads the created controls from viewstate that were bound to it.

So on subsequent requests, it loads the control hierarchy but knows nothing about the data source that created the UI unless you rebind again.

HTH.



来源:https://stackoverflow.com/questions/2325980/why-is-the-asp-net-repeater-items-collection-empty-when-controls-are-on-the-scr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!