4
votes
sUsername.Trim();
sPassword.Trim();
string ConnectionString = WebConfigurationManager.ConnectionStrings["dbnameConnectionString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(ConnectionString);

Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Any ideas? I don't understand the error.

5
Well, I do understand it, but you miss line references. Where does the error occur? - TomTom
WebConfigurationManager.ConnectionStrings["dbnameConnectionString"] returned null - tom
Two upvotes for this question? Seriously? - Kirk Broadhurst
Almost all cases of NullReferenceException are the same. Please see "What is a NullReferenceException in .NET?" for some hints. - John Saunders
Will someone please close this as a duplicate of stackoverflow.com/questions/4660142/…? - John Saunders

5 Answers

9
votes

Well, you haven't shown which line it occurs on. It suggests that one of these occurred:

  • sUsername was null
  • sPassword was null
  • WebConfigurationManager.ConnectionStrings["dbnameConnectionString"] returned null

Btw, calling Trim() as a statement on its own like that is pointless. Strings are immutable - Trim() returns the trimmed version. You want something like:

sUsername = sUsername.Trim();
sPassword = sPassword.Trim();

... but only after checking whether they're null or not.

4
votes

Well, I do understand it, but you miss line references. Where does the error occur?

Line 30:         sUsername.Trim();
Line 31:         sPassword.Trim();
Line 32:         string ConnectionString = WebConfigurationManager.ConnectionStrings["dbnameConnectionString"].ConnectionString;
Line 33:         SqlConnection myConnection = new SqlConnection(ConnectionString);
Line 34:         try

if I assume that sPassword exists - and sUsername... ...then does the ConnectionString "dbNameConnectionString" exist in the web.config? If not- that is null, and the ".ConnectionString" naturally throws that error.

1
votes

Line 30 and 31 don't do anything:

sUsername = sUsername.Trim();
sPassword= sPassword.Trim();

Post where the error occurs

0
votes

This just means that you're trying to access a member of a null reference; i.e. one of the variables here is null. Without knowing the line number it's difficult to say which, but I'd guess at either sUsername or sPassword.

0
votes

It happens because of any one of the variable is NULL. You can check the value of sUserName and sPassword variables during debugging (runtime).