Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Value not correct in OnInit 1

Status
Not open for further replies.

ghesse

Programmer
Jun 16, 2003
51
US
Hi,

I set a value of a property in the Page_Load event and then on a postback the value is not correct in the OnInit event. Can someone please tell me how to fix this?

private int _myprop = -1;
public int myproperty {
get{ return _myprop; }
set{ _myprop = value; }

override protected void OnInit(EventArgs e)
{
if( myproperty != -1 )
DoThis();
}

private void Page_Load( Object source, System.EventArgs e )
{
if( !IsPostBack )
myproperty = 1;
}

Ok so when I load up the page the value of myproperty changes to 1. Then on a postback OnInit should DoThis(). But it's not working. The value of myproperty is consistantly -1. Why is this and how can I fix it?

Thanks,
ghesse
 
From the code that you have provided the DoThis function will never get called as your property will always be -1 in the OnInit event. This is because the property value will be reset on every page call (which includes postback).
The first time the page is loaded then the page load event should set it to 1.

To persist the proper value of the property across a page call then you should store the value in the viewstate, rather than in a page level private variable. In VB.Net you would do the following:

Code:
Public myproperty() as integer
  Get
    if ViewState("myproperty") is nothing then
      ViewState("myproperty") = -1
    end if
    Return CType(ViewState("myproperty"), integer)
  End Get
  Set(byval Value as Integer)
    ViewState("myproperty") = Value
  End Set
End Property


James :)

James Culshaw
james@miniaturereview.co.uk
 
Ok that works great on the Page_Load event. But the OnInit is still not getting the correct value. This is very annoying, I think it has something to do with the order of events that happen on a page request.

--ghesse
 
Solved...

OnInit doesn't get the viewstate loaded before it's fired.

Solution, put the logic in LoadViewState!

Just make sure to include

base.LoadViewState

somewhere in it or the other ViewState will be inaccessible.

--ghesse
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top