Click here to Skip to main content
12,068,967 members (65,776 online)
Rate this:
 
Please Sign up or sign in to vote.
See more: ASP.NET
I have a Login problem in ASP.NET. I have two tables that has user information in them already. What I want my login to do is to check to see if the username exist within those tables. If they do then the user can make up a password and login. The username and password are now saved in the Security Table. How can I get it to check the user in both tables? And what did I do wrong within my code to get an error message: "Object reference not set to an instance of an object". It happens on this line of code: Line 51: string password = pass.ExecuteScalar().ToString();. Here is my whole code:

using System;
using System.Data;
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)
    {
        if (IsPostBack)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["PassConnectionString"].ConnectionString);
            con.Open();
            string cmdStr = "select count(*) from TableCEO where EmailAddress='" + TextBox1.Text + "'";
            SqlCommand userExist = new SqlCommand(cmdStr, con);
            int temp = Convert.ToInt32(userExist.ExecuteScalar().ToString());
            con.Close();
            if (temp == 1)
            {
                Response.Write("User Name Already Exist!!!");
            }
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["PassConnectionString"].ConnectionString);
        con.Open();
 
        string insCmd = "Insert into TableSecurity (EmailAddress, Password, Level) values (@EmailAddress, @Password, @Level)";
        SqlCommand insertUser = new SqlCommand(insCmd, con);
        insertUser.Parameters.AddWithValue("@EmailAddress", TextBox1.Text);
        insertUser.Parameters.AddWithValue("@Password", TextBox2.Text);
        insertUser.Parameters.AddWithValue("@Level", TextBox1.Text);
 

 

 
        string cmdStr = "select count(*) from TableCEO where EmailAddress='" + TextBox1.Text + "'";
            SqlCommand Checkuser = new SqlCommand(cmdStr, con);
            int temp = Convert.ToInt32(Checkuser.ExecuteScalar().ToString());
            if (temp == 1)
            {
                string cmdStr2 = "Select Password from TableSecurity where Password='" + TextBox2.Text + "'";
                SqlCommand pass = new SqlCommand(cmdStr2, con);
                string password = pass.ExecuteScalar().ToString();
                con.Close();
 
                if (password == TextBox2.Text)
                {
                    Session["New"] = TextBox1.Text;
                    Response.Redirect("Secure.aspx");
                }
                else
                {
                    Label1.Visible = true;
                    Label1.Text = "Invalid Password!!!";
                }
            }
            else
            {
                Label1.Visible = true;
                Label1.Text = "Invalid UserName!!!";
 
                
            }
        }
    }

Please Help me!!!
Posted 29-Apr-13 7:15am
Edited 29-Apr-13 7:23am
RyanDev193K
v2
Comments
ThePhantomUpvoter 29-Apr-13 12:24pm
   
You would get that error on that line because your SQL-injection-attack prone query is not returning anything.
Kwesi Hopkins 29-Apr-13 12:26pm
   
Ok. So, How to correct that problem?
ThePhantomUpvoter 29-Apr-13 12:28pm
   
Simple, either construct a query that returns a value or check the value that is being returned to make sure that it is not null.
Kwesi Hopkins 29-Apr-13 12:33pm
   
Can you give more of a code example?
ThePhantomUpvoter 29-Apr-13 12:40pm
   
Why? Do you not know how to check something for being null?
ExpertITM 29-Apr-13 12:43pm
   
You haven code for inserting into tablesecurity,
you are forgot to code executenonequery for insertUser
Kwesi Hopkins 29-Apr-13 12:41pm
   
Ok. This is what I did. I put in the code:

try
{
insertUser.ExecuteNonQuery();
con.Close();
}

finally
Now, When I try to login as that user I get this error:
Violation of PRIMARY KEY constraint 'PK_TableSecurity'. Cannot insert duplicate key in object 'dbo.TableSecurity'. The duplicate key value is (kwesihopkins@mail.com).
The statement has been terminated.

I can make a username and password but can't login as that user. How can I fix this problem?
ExpertITM 29-Apr-13 12:45pm
   
In security table which is your primary key?
Kwesi Hopkins 29-Apr-13 12:51pm
   
EmailAddress is the primary key.
ExpertITM 29-Apr-13 12:53pm
   
first check email is exists or not in table if exists then login that user otherwise insert into table,
I write code below,
Just try it and tell me
Thanks.
ExpertITM 29-Apr-13 12:50pm
   

string chkUser = "select count(*) from TableSecurity where EmailAddress = 'textbox1.text' and Password ='textbox2.text') ;
SqlCommand chkUsercmd = new SqlCommand(chkUser, con);
int i = cmd.executeScaler();
if(i<1)
{



string insCmd = "Insert into TableSecurity (EmailAddress, Password, Level) values (@EmailAddress, @Password, @Level)";
SqlCommand insertUser = new SqlCommand(insCmd, con);
insertUser.Parameters.AddWithValue("@EmailAddress", TextBox1.Text);
insertUser.Parameters.AddWithValue("@Password", TextBox2.Text);
insertUser.Parameters.AddWithValue("@Level", TextBox1.Text);

}
else
{
Session["New"] = TextBox1.Text;
Response.Redirect("Secure.aspx");
}
Kwesi Hopkins 29-Apr-13 12:52pm
   
Where should I put this code?
ExpertITM 29-Apr-13 12:59pm
   
put above the insert opration,
this code is for checking user exists or not
Kwesi Hopkins 29-Apr-13 13:05pm
   
Ok. I did that but I have an error. The name cmd does not exist in the current context.
This is before I ran it. in my error list box.
ExpertITM 29-Apr-13 13:18pm
   
replace cmd to chkUsercmd
Kwesi Hopkins 29-Apr-13 13:24pm
   
Ok. I did that and I got this:
Cannot implicitly convert type 'object' to 'int'. An explicit conversion exists (are you missing a cast?)

What does this mean?
ExpertITM 29-Apr-13 13:31pm
   
replace,
int i = cmd.executeScaler();
to
int i = convert.ToInt16(cmd.executeScaler());
Kwesi Hopkins 29-Apr-13 13:42pm
   
Ok. I had to change somethings and add some but it worked. How can I write a single string to include two tables. In other words. How can I check two tables for the username and then go from there?
ExpertITM 29-Apr-13 13:43pm
   
find in google for example of executereader
you can get idea
Kwesi Hopkins 29-Apr-13 13:45pm
   
Did you read my last question?
ryanb31 29-Apr-13 12:56pm
   
First off, the error on .ToString() on ExecuteScalar() means the query did not return anything so you cannot call .ToString() on a null. Do Object test = ...ExecuteScalar() and then if (test != null) Secondly, to check the second table just write the sql. Do an inner join.
Kwesi Hopkins 29-Apr-13 12:57pm
   
Thanks ryanb31. I did that and corrected the code from there. I am about to rebuild and run it again.

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


Advertise | Privacy | Mobile
Web04 | 2.8.160208.1 | Last Updated 29 Apr 2013
Copyright © CodeProject, 1999-2016
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100