views:

226

answers:

3

Hi all,

I have a UserControl called 'Inspirations' with the following public property

private int pagenumber;
public int PageNumber
{

    get { return pagenumber; }
    set { pagenumber = value; }

}

On my aspx page I set the value of the property like so:

Inspirations.PageNumber = (int)Convert.ToInt32(this.txtNum.Text);

On my aspx page I write back the value to check its been set:

Response.Write(Inspirations.PageNumber.ToString());

...and it has on my aspx page.

However, I have a button on my UserControl to test the value of PageNumber and when I click that it always comes back as zero.

protected void btnAddCompany_Click(object sender, EventArgs e)
{
    Response.Write(PageNumber.ToString());
}

...the property value doesn't seem to have been passed back to my control.

Can anyone tell me what I'm doing wrong, please.

Regards Melt

A: 

Your button click will be actioned via postback which means other methods (e.g. OnInit(), OnLoad()) in the ASP.NET Page lifecycle will still be called.

If you are setting PageNumber in one of these it will obliterate the value set from the browser before it gets to your button click handler.

Check the IsPostBack property before setting a property/field value to prevent this.

Alan Christensen
A: 

You need to persist the value in ViewState or SessionState:

eg:

public int PageNumber
        {
            get
            {
                if (ViewState["PageNumber"] == null || ViewState["PageNumber"].ToString().Trim() == String.Empty)
                {
                    ViewState["PageNumber"] = 0;
                }
                return Int32.Parse(ViewState["PageNumber"].ToString().Trim());
            }
            set
            {
                ViewState["PageNumber"] = value;
            }
        }
Mark Redman
Thanks a lot for that working solution
Melt
..and thanks everyone for all the replies
Melt
A: 

The sequence of events/phases in an aspx page includes the following (this is a partial list):

  1. OnInit (controls first, then page)
  2. OnLoad (page first, then controls)
  3. Control events (such as a button press)
  4. PreRender
  5. Render

Any code you have in the markup side of things is called during the Render phase.

In general, calling Response.Write() is not safe except during Render. If you call it before then, any output will appear before all of your markup.

So, the answer to your question: first, this all needs to happen during the same request, since just storing a public property won't persist value across requests. Next, make sure you set the property early in the life cycle (usually OnLoad). Next, don't use Response.Write() to output the results. Set the value of an <asp:Label> control, or something like that.

RickNZ