0

ASP.NET w/ C#

I'm collecting data from 5 textboxes. After data is input, a submit button is clicked to send the data to be displayed on another form, and hopefully save it to a database.

Upon clicking 'submit'

I get NullReferenceException was unhandled by user code

this is highlighted in that form's code behind...

if (clsDataLayer.SavePersonnel(Server.MapPath("PayrollSystem_DB.mdb"),
     Session["FirstName"].ToString,
     Session["LastName"].ToString,
     Session["PayRate"].ToString,
     Session["StartDate"].ToString,
     Session["EndDate"].ToString()))

any ideas? I'm not very experienced. Thanks in advance!!

4
  • One of your session variables is probably null. How are those getting set? If they are all good then it could be the error bubbling up from the SavePersonnel method Commented Jan 31, 2012 at 21:38
  • Are the values you're looking for really saved in the Session object? You're sure you don't mean to use Request.Form instead of Session? Commented Jan 31, 2012 at 21:39
  • John Saunders has put together this generic question in order to address questions along the lines of "Why am I getting a NullReferenceException?" Maybe this will help point you in the right direction. However, I agree with Chris and Joachim; it seems likely that one of the values that you expect to be in Session is really not. Commented Jan 31, 2012 at 21:40
  • is session variable are set? is that where the error thrown? Commented Jan 31, 2012 at 21:40

3 Answers 3

1

Session["Key"] returns an object. IF that object is null, then calling ToString() on it would generate a null reference exception.

You need to check if each of the fields you're checking is not null first. e.g.

(Session["FirstName"] != null) 
     ? Session["FirstName"] 
     : String.Empty;
Sign up to request clarification or add additional context in comments.

Comments

0

Either clsDataLayer is NULL, or one of the 5 values that you have in session don't exist. You must test for null values.

BTW, you're missing () after ToString in 4 places; I'm surprised that even compiles.

2 Comments

sorry - typo - () is after every ToString
ok, then what @Shredder suggested above is probably what you're missing: Session["FirstName"] = txtFirstName.Text; somewhere before your if statement.
0

You need to make sure that you have set these Session variables before you retrieve them. Within the user's session, at some point, you should have set these session variables like

Session["FirstName"] = txtFirstName.Text;
//etc

You can do a check before you use them to make sure they are not null, like

if(Session["FirstName"] != null){}

Also, when you use the .ToString() method, make sure to append the () (as you did for the last one) to all.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.