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!!

a bc
  • 9
  • 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 – Chris Jan 31 '12 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? – Joachim Isaksson Jan 31 '12 at 21:39
  • John Saunders has put together [this generic question](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net) 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. – Dr. Wily's Apprentice Jan 31 '12 at 21:40
  • is session variable are set? is that where the error thrown? – AJP Jan 31 '12 at 21:40

3 Answers3

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;
Eoin Campbell
  • 43,500
  • 17
  • 101
  • 157
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.

Nick Rolando
  • 25,879
  • 13
  • 79
  • 119
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.

  • sorry - typo - () is after every ToString – a bc Jan 31 '12 at 21:50
  • ok, then what @Shredder suggested above is probably what you're missing: `Session["FirstName"] = txtFirstName.Text;` somewhere before your `if` statement. –  Jan 31 '12 at 21:53