Scope and values of Object

G

Guest

I'm trying to set a level of abstraction in an ASP.NET app. I've created an
object with properties and methods that I instansiate just after the class
declaration. As I'm debugging this code I find that on postback the object is
re-instanciated, wiping all the property values. A simplified version of what
I'm trying to do is as follows:

Using System;
Using ...

namespace Test
public class Test
{
Obj o = new Obj;

private void Page_Load(object sneder, System.EventArgs e)
{
if (! IsPostBack)
{
o.property1 = true;
}
}
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.submit.Click += System.EventHandler(this.submit_click);
}
private void submit_click()
{
Response.Write("<script language='javascript'> {alert("Value
of o.Property1 = " + o.Property1);}</script>");
}
}

After postback, the object is instanciated (again) and all the properties
are reset. How do I keep the scope (and values) throught the life of the form?

Thanks!
 
G

Guest

You will have to use a ViewState to persist your object, and also ensure that
object can be serialized. Make following changes to your Page_Load

Obj o = null;
....
private void Page_Load(object sneder, System.EventArgs e)
{
if (! IsPostBack)
{
o = new Obj();
o.property1 = true;
//save it in page's view state
ViewState["myObject"] = o;
}

o = ViewState["myObject"] as Obj;
}

After this your submit click should work just fine, and object will get
instantiated only when page is not posted back, and then saved into the view
state.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top