test
test

Reputation: 2618

IsPostback Customized

I am trying to create my 'custom IsPostBack', all I did was create a bool property,

bool test;
public bool MyPostBack
{
    get{ test = Page.IsPostBack; return test; }
    set{ test = value; }
}

when debugging, having set, eg, value to false, when test is true, after pressing F11, test remains as it is! I find this very strange. Do you have any idea why? Thank you.

Upvotes: 0

Views: 172

Answers (3)

Ben
Ben

Reputation: 423

I like to suggest another way to do this. Most likely that you would like to keep this in the session, so you can do the following:

public bool MyPostBack
{
   get
   {
        if (Session["MyPostBack"] == null)
            Session["MyPostBack"] = Page.IsPostBack;

        return (bool)Session["MyPostBack"];
   }
   set
   {
        Session["MyPostBack"] = value;
   }
}

That way, MyPostBack will always return a valid value, even if you did not initialize it. It will be available even prior to Page_Load (in Page_Init, for example).

I also think it would be better not to have a setter for it at all, but have some more calculations in the getter. Otherwise, from my experience, when setting its value in more than one or two cases, the code may become unreadable and not very easy to maintain.

Upvotes: 0

Matt Varblow
Matt Varblow

Reputation: 7891

The first thing you're doing in the property getter is reseting it:

test = Page.IsPostBack;

So, setting your MyPostBack property will have basically no effect because the value you set it to is overridden every time you get the property value.

You probably want something more like this:

bool test;

public bool MyPostBack
{
    get{ return test; }
    set{ test = value; }
}

protected void Page_Load(object sender, EventArgs e)
{
     MyPostBack = Page.IsPostBack;
}

The private variable (test) is initialized in the Page Load event to the value of the page's IsPostBack property.

Upvotes: 6

SLaks
SLaks

Reputation: 887459

Every time you read the property, your getter resets the field to the original Page.IsPostBack.

Upvotes: 2

Related Questions