[newbie] need help on this NULL object reference

J

Jeff

Hey

asp.net 2.0

Below is the code I have behind a web page. The problem is during runtime in
btnSave_Click, userProfile has a NULL value. I don't understand why it has a
NULL value, because AFAIK I've declared userProfile as a class variable so
the value it has in btnSave_Click should be the value it did get in
Page_Load. userProfile get a value in Page_Load - but is NULL in
btnSave_Click

What am I doing wrong here?

public partial class EditUser : System.Web.UI.Page
{
private ProfileCommon userProfile;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string username = Request.QueryString["user"].ToString();
if (username.Length > 0)
{
userProfile = Profile.GetProfile(username);
this.Settings1.SetText(userProfile);
}

}
}


protected void btnSave_Click(object sender, EventArgs e)
{
this.Settings1.SaveInfo(userProfile);
}
}
 
M

Mark Fitzpatrick

First, you always need to check your Request.QueryString variables to ensure
they aren't null.

You'll need to add an

if(Request.QueryString["user"] != null)

condition check.

The thing to keep in mind, the userprofile is set when you first load the
page. It is not loaded the second time because you're only loading it if it
isn't a postback. Keep in mind, setting a variable in a web form is not like
setting a variable in a windows form, the state is not maintained betwee
postbacks unless you create a mechanism to save the state of the item. You
could try saving the profile into the viewstate and then fetching it back on
subsequent calls. Possibly by creating a property that looks something like:

private ProfileCommon UserProfile
{
get{
if(ViewState["userprofile"] != null)
return (ProfileCommon)ViewState["userprofile"];
else
return null;
}
set
{
ViewState["userprofile"] = value;
}
}

Will this work? I don't know. I haven't tried to do this one before and I'm
not sure if the profile can be serialized into the viewstate or not. The
bottom line though, unless you can find a way to maintain the state of the
profile you'll have to remove the !Page.Ispostback check.
 

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

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,015
Latest member
AmbrosePal

Latest Threads

Top