Maninder
Maninder

Reputation: 1261

ListView.DataItem is showing null

Listview binding code

<asp:Content ID="Content3" ContentPlaceHolderID="leftColumnPlaceHolder" runat="server">
    <asp:ListView ID="lvQuestions" runat="server" OnItemDataBound='lvQuestions_ItemDataBound'>
        <LayoutTemplate>
            <div id="itemPlaceholder" runat="server">
            </div>
            <asp:Button ID="btnSubmitAnswers" runat="server" Text="Submit Answers" OnClick="btnSubmitAnswers_Click" />
        </LayoutTemplate>
        <ItemTemplate>
            <div>
                <%# Container.DataItemIndex + 1 %>:<%# Eval("Body") %>
            </div>
            <asp:RadioButtonList ID="rdlAnswers" runat="server" DataSource='<%#Eval("ExamAnswer") %>' DataTextField='Body' DataValueField="AnswerId">
            </asp:RadioButtonList>
        </ItemTemplate>
    </asp:ListView>
</asp:Content>

While fetching the listview items on submit button click..like below, we are getting qsnItem.DataItem as NULL.

foreach (ListViewDataItem qsnItem in lvQuestions.Items)
{
}

Please suggest what is going wrong here.

Upvotes: 0

Views: 3373

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460138

The DataItem of all databound web-controls in ASP.NET are null on postbacks when you don't DataBind the control again, which is unnecessary when ViewState is enabled(default).

So you can use the controls in your templates to get the values:

foreach (ListViewDataItem qsnItem in lvQuestions.Items)
{
    RadioButtonList rdlAnswers = (RadioButtonList)qsnItem.FindControl("rdlAnswers");
}

If you need to old values you need to load them from database or use the ListViewUpdatedEventArgs.OldValues Property.

Upvotes: 5

Related Questions