1

I read the other answers on here but nothing has worked. The issue is if the user enters an incorrect password I get this error (username is fine):

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

Stack trace:

[NullReferenceException: Object reference not set to an instance of an object.]
   Login.btnLogin_Click(Object sender, EventArgs e) in c:\Users\Michelle\Desktop\COMF510_65300_HS_task_2\Login.aspx.cs:31
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9628614
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +103
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1724

the login.aspx.cs :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;

public partial class Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnLogin_Click(object sender, EventArgs e)
    {
        SqlConnection myDB = new SqlConnection(ConfigurationManager.ConnectionStrings["LoginConnectionString"].ConnectionString);
        myDB.Open();
        string checkUser = "select count (*) from users where username = '"+txtUserName.Text+"'";
        SqlCommand com = new SqlCommand(checkUser, myDB);
        int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
        myDB.Close();

        if (temp == 1)
        {
            myDB.Open();
            string checkPassWord = "select password from users where password = '" + txtPassword.Text + "'";
            SqlCommand passCom = new SqlCommand(checkPassWord, myDB);
            string pass = passCom.ExecuteScalar().ToString().Replace(" ","");
            if(pass == txtPassword.Text)
            {
                Session["New"] = txtUserName.Text;
                Response.Redirect("EmpWelcome.aspx");
            }
            else
            {
                Response.Write("Incorrect details!  Please try again.");// if password is incorrect
            }
        }
        else
        {
            Response.Write("Incorrect details!  Please try again."); // if username is incorrect
        }
    }
}

the source error:

Line 31: string pass = passCom.ExecuteScalar().ToString().Replace(" ","");

I'm sure it is an easy fix for experts but I am pretty new in C#. Thank you in advance.

user3515765
  • 307
  • 2
  • 12
  • 1
    Either `passComm` or the result of `ExecuteScalar` is `null`. – easuter May 12 '15 at 10:48
  • @ D Gibbs Like i have said I already checked out that post. I am new so the extensive explanation is not newbie friendly! A simple explanation and an example goes a long way. Thanks for your input. – user3515765 May 12 '15 at 10:50
  • `int temp= Convert.ToInt32(com.ExecuteScalar());` try this – Pradnya Bolli May 12 '15 at 10:51
  • `string pass = passCom.ExecuteScalar() ?? string.empty;` Replace your line 31 with this code. – geo May 12 '15 at 10:54
  • `string pass = string.Empty; var exec = passCom.ExecuteScalar(); if (exec !=null && !string.IsNullOrEmpty(exec.ToString())) { pass = exec.ToString(); pass.Replace(" ", ""); if (pass == txtPassword.Text)\{Session["New"] = txtUserName.Text; Response.Redirect("EmpWelcome.aspx"); } else { Response.Write("Incorrect details! Please try again."); }}` – Mirza Danish Baig May 12 '15 at 11:03
  • Thank you for your help guys. Very much appreciated. – user3515765 May 12 '15 at 11:13
  • 2
    By the way, your code has a fatal flaw (other than SQL injection attacks), since you don't validate the user name and password **together**, if you enter *any* valid user and *any* valid password (even one from another user), your code will validate the user and let them through. – Ron Beyer May 12 '15 at 11:58
  • Thats ok for now as it is a task and wont go live. But thank you for the input :) – user3515765 May 12 '15 at 12:08

1 Answers1

1

com.ExecuteScalar() is null (no results were found)

Try following code (and also don't remember dispose db objects by using constructions).

protected void btnLogin_Click(object sender, EventArgs e)
{
    using (SqlConnection myDB = new SqlConnection(ConfigurationManager.ConnectionStrings["LoginConnectionString"].ConnectionString))
    {
        myDB.Open();
        string passwordObject = "select password from users where username = '" + txtUserName.Text + "'";
        using (SqlCommand com = new SqlCommand(passwordObject, myDB))
        {
            var res = com.ExecuteScalar();
            if (res != null)
            {
                string checkPassWord = passwordObject as string;
                if (txtPassword.Text == checkPassWord)
                {
                    Session["New"] = txtUserName.Text;
                    Response.Redirect("EmpWelcome.aspx");
                }
                else
                {
                    Response.Write("Incorrect details!  Please try again.");// if password is incorrect
                }
            }
            else
            {
                Response.Write("Incorrect details!  Please try again."); // if username is incorrect
            }
        }
    }
}
General-Doomer
  • 2,545
  • 11
  • 13