回发时FormView.DataItem为null

Hof*_*off 3 .net c# asp.net

我在ASP.NET页面上使用LinqDataSource和FormView并启用了分页.我试图访问FormView的DataItem属性PageLoad,我在第一页加载时没有任何问题,但只要我在FormView上使用Next/Prev页面按钮(导致回发),DataItem属性为null,即使有记录在FormView中显示.任何想法为什么它在第一页加载但不在回发上正常工作?

如果你很好奇我的PageLoad活动是什么样的,这里是:

protected void Page_Load(object sender, EventArgs e)
{
    Label lbl = (Label)fvData.FindControl("AREALabel");
    if (fvData.DataItem != null && lbl != null)
    {
        INSTRUMENT_LOOP_DESCRIPTION record = (INSTRUMENT_LOOP_DESCRIPTION)fvData.DataItem;
        var area = db.AREAs.SingleOrDefault(q => q.AREA1 == record.AREA);
        if (area != null)
            lbl.Text = area.AREA_NAME;
    }
}
Run Code Online (Sandbox Code Playgroud)

Jup*_*aol 5

绑定到任何数据绑定控件的对象将不会保留在页面的ViewState中

因此,在后续帖子中,DataItem除非重新绑定控件,否则该属性将为null

绑定控件时,此属性将包含对象的引用.

通常,如果要在绑定对象时执行某些操作,则需要访问此属性,因此需要对DataBound事件做出反应

例:

产量

在此输入图像描述

代码背后

protected void ds_DataBound(object sender, EventArgs e)
{
    var d = this.fv.DataItem as employee;
    this.lbl.Text = d.lname;
}
Run Code Online (Sandbox Code Playgroud)

ASPX

    <asp:LinqDataSource ID="lds" runat="server"
        ContextTypeName="DataClassesDataContext"
        TableName="employees" 
    >

    </asp:LinqDataSource>
    <asp:FormView runat="server" ID="fv" DataSourceID="lds" AllowPaging="true" 
        OnDataBound="ds_DataBound">
        <ItemTemplate>
            <asp:TextBox Text='<%# Bind("fname") %>' runat="server" ID="txt" />
        </ItemTemplate>
    </asp:FormView>
    <br />
    <asp:Label ID="lbl" runat="server" />
Run Code Online (Sandbox Code Playgroud)