问题
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.
回答1:
Well, you haven't shown which line it occurs on. It suggests that one of these occurred:
sUsername
was nullsPassword
was nullWebConfigurationManager.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.
回答2:
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.
回答3:
Line 30 and 31 don't do anything:
sUsername = sUsername.Trim();
sPassword= sPassword.Trim();
Post where the error occurs
回答4:
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
.
回答5:
It happens because of any one of the variable is NULL. You can check the value of sUserName
and sPassword
variables during debugging (runtime).
来源:https://stackoverflow.com/questions/2491721/object-reference-not-set-to-an-instance-of-an-object-5