我正在使用 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
例子:
输出
代码隐藏
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/