views:

156

answers:

3

Please help me to figure out what is wrong with this code:

I have ASP.NET page with one button visible.

When user clicks it - it instances MyClass (its implementation is in AppCode directory) and turns invisible (button2 becomes visible).

When I click button2 it raises "Object reference not set to an instance of an object" Exception.

What seems to be the problem?

{

public MyClass noviTest;

 protected void Page_Load(object sender, EventArgs e)
 {
 }
 protected void Button1_Click(object sender, EventArgs e)
 {
    noviTest = new MyClass(TextBox1.Text);
    Button1.Visible = false;
    Button2.Visible = true;

 }
 protected void Button2_Click(object sender, EventArgs e)
 {
    Label1.Text=noviTest.getID; //this is the critical line

 }
}
+1  A: 

noviTest is null inside Button2_Click.

Try something like this:

protected void Page_Load(object sender, EventArgs e)
{
    noviTest = new MyClass(TextBox1.Text);
}
protected void Button1_Click(object sender, EventArgs e)
{
    Button1.Visible = false;
    Button2.Visible = true;    
}
protected void Button2_Click(object sender, EventArgs e)
{
    Label1.Text = noviTest.getID;
}

This will cause noviTest to be instantiated on each page request, regardless of which button was clicked. This may not be the best solution for your particular application (I am unfamiliar with the rest of the logic in this class) but you get the idea.

Andrew Hare
+4  A: 

Since on postback the noviTest reference to MyClass is not recreated.

You can add it to the viewstate to keep a reference to it. (Assuming MyClass is serializable).
In Button1_Click:

ViewState("noviTest") = noviTest;

Then in Button2_Click:

var noviTest = ViewState("noviTest");
Sani Huttunen
Thank you.I tried this and error sais "The name 'ViewState' does not exist in the current context"???
nanek
+1  A: 

Each visit to the code-behind is kind of like running the code from scratch, nothing is set up or preserved for you between visits to page.

So when you hit the second button noviTest is not initialised and therefore when you attempt to call .getID to you get a null reference exception.

To deal with this you need to ensure that noviTest is initialised. If you want to have it persisted between visits to the page you need to use some mechanism to either store or recreate the instance. To store it you would (probably) use session. To recreate you would use either session or viewdata to persist a key value that would then allow you to retrieve the object state from storage of some kind.

Murph
I tried to use viewstate, but I think session is only solution for me. :)
nanek