Postbacks and Databinding -- Skipping through part of the page lifecycle?
Ok, I have a UserControl. In it is a textbox and other such things and a save button.
I have this UserControl within a Repeater control in the ItemTemplate.
Now whenever I first run it, it seems to work fine. When I change the contents of the textbox and go to save it however I get all sorts of null reference errors.
The most confusing part is that it seems to create a new instance of my class, but skips over the Page_Load
method and such. This is a sample of my code in the UserControl
Data.Report ThisReport;
[Browsable(true)]
public int ReportID
{
get;
set;
}
protected void Page_Load(object sender, EventArgs e)
{
if (ReportID == 0)
{
throw new ArgumentException("ReportID can not be 0");
}
var report = Data.Report.SingleOrDefault(x => x.ID==ReportID);
txtName.Text = report.Description;
ThisReport = report;
}
protected void btnSave_Click(object sender, EventArgs e)
{
var x=ThisReport.Foo; //ThisReport == null here.
}
It is used in the repeater lik开发者_开发百科e this:
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="ReportsData">
<ItemTemplate>
<uc:ReportManager ReportID="<%# ((Data.Report)Container.DataItem).ReportID %>"
runat="server" />
</ItemTemplate>
</asp:Repeater>
Why does it seem to initialize a new instance of my UserControl? How do I overcome this problem?
Looks like you control is only bound 1 time, so ReportID doesn't get the right value, and
var report = Data.Report.SingleOrDefault(x => x.ID==ReportID);
returns null.
Have you tried putting ReportID in viewstate ?
public override int ReportID
{
get
{
if (this.ViewState["ReportID"] == null)
{
throw new ArgumentException("ReportID can not be 0");
}
return (int)this.ViewState["ReportID"];
}
set
{
this.ViewState["ReportID"] = value;
}
}
精彩评论