c# - FormView.DataItem 在回发时为 null

标签 c# asp.net .net

我正在使用 LinqDataSource 和在 ASP.NET 页面上启用分页的 FormView。我正在尝试访问 PageLoad 上的 FormView 的 DataItem 属性,我在第一页加载时没有遇到任何问题,但是一旦我使用 Next/Prev 页面按钮(导致一个回发)在 FormView 上 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;
    }
}

最佳答案

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

因此,在后续的帖子中,DataItem 属性将为空,除非您重新绑定(bind)控件

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

如果您想在绑定(bind)对象时执行某些操作,通常您需要访问此属性,因此您需要对DataBound 事件使用react

例子:

输出

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

关于c# - FormView.DataItem 在回发时为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11547125/

相关文章:

javascript - 将多个字符串值作为参数从服务器端传递给 JavaScript 函数

c# - 数据网格取消编辑不起作用

c# - 基于 ViewModel 状态显示 UI 错误消息的最佳实践

c# - SCardEstablishContext 内存泄漏

c# - 如何在 ASP.NET 中显示 "View"表(SQL 表)?

asp.net - 从DataTable中删除空行的方法?

c# - .NET 异步 MSMQ

c# - 为什么有时 WebBrowser.Dispose() 会启动 Internet Explorer?

c# - Windows 服务 OnPowerEvent

c# - 在与 ASP.Net 中的搜索控件相同的页面上显示搜索结果的最佳方式