Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
4.20/5 (2 votes)
See more:
This code below if you enter the correct username and password it does work but the only proble is when i type the wrong password it display this message "Object reference not set to an instance of an object. "

Here is my code
C#
string username = loginDetails.UserName;
           string pwd = loginDetails.Password;

           string s;
           s = WebConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
           SqlConnection con = new SqlConnection(s);
           con.Open();
           string sqlUserName;
           sqlUserName = "SELECT * FROM ADMINISTRATOR WHERE Admin_Username ='" + username + "' AND Admin_Password ='" + pwd + "'";
           SqlCommand cmd = new SqlCommand(sqlUserName, con);

           string CurrentName;
           CurrentName = (string)cmd.ExecuteScalar().ToString();

           if (CurrentName != null)
           {
               Session["UserAuthentication"] = username;
               Session.Timeout = 1;
               Response.Redirect("~/Admin/Default.aspx");
           }
           else
           {
               Session["UserAuthentication"] = "";
           }


Please you can also help me with dispalying the username to the page i call when the username and password is true(correct). like Welcome Timothy
Posted

This is returning null when you enter wrong password:

cmd.ExecuteScalar()


check for null before doing tostring()
 
Share this answer
 
You did not show where the exception with the message "Object reference not set to an instance of an object" is thrown.

Not to worry. This is one of the very easiest cases to detect and fix. It simply means that some member/variable of some reference type is dereferenced by using and of its instance (non-static) members, which requires this member/variable to be non-null, but in fact it appears to be null. Simply execute it under debugger, it will stop the execution where the exception is thrown. Put a break point on that line, restart the application and come to this point again. Evaluate all references involved in next line and see which one is null while it needs to be not null. After you figure this out, fix the code: either make sure the member/variable is properly initialized to a non-null reference, or check it for null and, in case of null, do something else.

Please see also: want to display next record on button click. but got an error in if condition of next record function "object reference not set to an instance of an object"[^].

Sometimes, you cannot do it under debugger, by one or another reason. One really nasty case is when the problem is only manifested if software is built when debug information is not available. In this case, you have to use the harder way. First, you need to make sure that you never block propagation of exceptions by handling them silently (this is a crime of developers against themselves, yet very usual). The you need to catch absolutely all exceptions on the very top stack frame of each thread. You can do it if you handle the exceptions of the type System.Exception. In the handler, you need to log all the exception information, especially the System.Exception.StackTrace:
http://msdn.microsoft.com/en-us/library/system.exception.aspx[^],
http://msdn.microsoft.com/en-us/library/system.exception.stacktrace.aspx[^].

The stack trace is just a string showing the full path of exception propagation from the throw statement to the handler. By reading it, you can always find ends. For logging, it's the best (in most cases) to use the class System.Diagnostics.EventLog:
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx[^].

Good luck,
—SA
 
Share this answer
 
v2
Comments
joshrduncan2012 11-Jun-13 10:01am    
Very thorough. Great job. My +5.
Sergey Alexandrovich Kryukov 11-Jun-13 10:35am    
Thank you very much,
—SA
1) Login Problem:

Simplest way to overcome this type of issue:

C#
SqlCommand cmd = new SqlCommand(sqlUserName, con); //Here you are advised to use parameterized query
SqlDataReader dr= cmd.ExecuteReader();
if(dr.read())
{
    Session["UserAuthentication"] = username;
    Session.Timeout = 1;
    Response.Redirect("~/Admin/Default.aspx");
}
else
{
    Response.Write("<script type='text/javascript'>");
    Response.Write("alert('Wrong credentials.');");
    Response.Write("</script>");
}

2) Display username after login:

Refer to below link where i answered exactly the same issue just before some minutes

how to display firstname and last name after login using label[^]

Regards... :laugh:
 
Share this answer
 
v3
HEllO
YOUR PROBLEM RESOLVE BY THIS CODE


C#
var   CurrentName = cmd.ExecuteScalar();

   if (CurrentName != null)
   {

       Session["UserAuthentication"] = username;
       Session.Timeout = 1;
       Response.Redirect("~/Admin/Default.aspx");
   }
   else
   {
       Session["UserAuthentication"] = "";
   }
 
Share this answer
 
I'm surprised no-one mentioned this, but the way you are doing the name/password check is vulnerable to SQL Injection attack.

You should read up on this. The basic thing is because you are building up your query string without validating the username and password it's easy to abuse the query string.

If I enter ' or 1 = 1-- as the username with any password the query becomes:

SELECT * FROM ADMINISTRATOR WHERE Admin_Username ='' or 1 = 1 --' AND Admin_Password ='hhh'

And that will get me in without knowing either username or password. Try it!

You should parametrize username and password and set them on the SqlCommand!
 
Share this answer
 
string sqlUserName;

"Object reference not set to an instance of an object." this error may be comes when value is null

check whether the values are null or not by using break point and press F11 or F10

sqlUserName value will be empty because u are using and operator.

if both conditions become true means it will return some values. u are entering wrong values so conditions become false.
 
Share this answer
 
v3
make some changes with your...........

SqlCommand cmd = new SqlCommand(sqlUserName, con);

DataAdaplter da = new DataAdaplter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);

if(ds.Tables[0].Rows.Count !=0)
{
Session["UserAuthentication"] = ds.Tables[0].Rows[0]["Admin_Username"].ToString();
//And redirect to home page
}
else
{
Responce.Write("Incorrect UserName and Password....!");
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900