Reputation: 1772
I am using a LinqDataSource and a FormView with paging enabled on an ASP.NET page. I am trying to access the FormView's DataItem
property on PageLoad
and I have no trouble on the first page load, but as soon as I use the Next/Prev page button (causing a postback) on the FormView the DataItem
property is null, even if there a record showing in the FormView. Any ideas why it works fine on the first page load but not on a postback?
If you're curious what my PageLoad
event looks like, here it is:
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;
}
}
Upvotes: 4
Views: 4639
Reputation: 21365
The object you bind to any data-bound control won't be persisted in the page's ViewState
Therefore, on subsequent posts the DataItem
property will be null unless you re-bind the control
This property will contain a reference to the object when the control is bound.
Usually you would need to access this property if you want to do something when the objects is bound, so you need to react to the DataBound
event
Example:
protected void ds_DataBound(object sender, EventArgs e)
{
var d = this.fv.DataItem as employee;
this.lbl.Text = d.lname;
}
<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" />
Upvotes: 5
Reputation: 609
Your data will not be preserved on PostBack
. You'll need to rebind the FormView
in the PageIndexChanging
event using something like:
protected void FormView_PageIndexChanging(object sender, FormViewPageEventArgs e)
{
FormView.PageIndex = e.NewPageIndex;
//rebind your data here
}
Upvotes: 0