回发时FormView.DataItem为null

时间:2012-07-18 17:35:18

标签: c# asp.net .net

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

如果您对我的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;
    }
}

2 个答案:

答案 0 :(得分:5)

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

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

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

如果你想在绑定对象时做某事,你通常需要访问这个属性,所以你需要对DataBound事件作出反应

示例:

输出

enter image description here

背后的代码

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

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" />

答案 1 :(得分:0)

您的数据不会保留在PostBack上。您需要使用以下内容重新绑定FormView事件中的PageIndexChanging

protected void FormView_PageIndexChanging(object sender, FormViewPageEventArgs e)
{
    FormView.PageIndex = e.NewPageIndex;
    //rebind your data here
}
相关问题