views:

17

answers:

1

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 like 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?

A: 

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;
    }
}
mathieu
no, the `var report=...` returns a valid report object. The problem is that when the save event gets called, it gets called upon a new instance of the class where Page_Load has not been called. Also, I have ViewState disabled on this particular page.
Earlz
I don't see why ViewState would even be needed, I mean this is all happening in one single request!
Earlz