Object reference not set to instance of object # 5

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

The reference to the object is not installed in the instance of the object. Description: An unhandled exception occurred during the execution of the current web request. Check the stack trace for more information about the error and where it appeared in the code.

Exception Details: System.NullReferenceException: The object reference was not set to the object instance.

Any ideas? I do not understand the error.

+4
source share
5 answers

Well, you did not indicate on which line this is happening. This suggests that one of them happened:

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

Btw, calling Trim() as a statement in itself is pointless. Lines are immutable - Trim() returns the cropped version. You want something like:

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

... but only after checking if they are null or not.

+9
source

Ok, I understand that, but you are missing links on the line. 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 sPassword exists - and sUsername ... ... then does the web.config ConnectionString "dbNameConnectionString" exist? If not, then null, and ".ConnectionString" naturally throws this error.

+4
source

Lines 30 and 31 do nothing:

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

Error message

+1
source

This means that you are trying to access a null reference element; that is, one of the variables here is null . Without knowing the line numbers, it's hard to say that, but I would have guessed that in sUsername or sPassword .

0
source

This is due to any one of the NULL variables. You can check the values ​​of the sUserName and sPassword during debugging (runtime).

0
source

Source: https://habr.com/ru/post/1304755/


All Articles