Click here to Skip to main content
15,893,486 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
i need some help

C#
protected void btnLogin_Click(object sender, EventArgs e)
        {
            string query = "Select Count(*) From LoginInfo Where lo_name = @username And lo_password = @password";
            int userId = 0;
            using (SqlConnection conn = new SqlConnection(conStr))
            {
                using (SqlCommand cmd = new SqlCommand(query, conn))
                {
                    cmd.CommandType = CommandType.Text;
                    cmd.Parameters.AddWithValue("@username", txtUsername.Text);
                    cmd.Parameters.AddWithValue("@password", txtPassword.Text);
                    cmd.Connection = conn;
                    conn.Open();
                    userId = Convert.ToInt32(cmd.ExecuteScalar());
                    conn.Close();
                }
                if(userId>0)
                {
                    Response.Redirect("Default.aspx");
                }
                else
                {
                    lable1.Text = "Login Fialed";
                }
            }
            
        }

when i clicked on login button it give error on the following codes

C#
userId = Convert.ToInt32(cmd.ExecuteScalar());
Posted
Comments
Patrice T 19-Aug-15 2:13am    
Which error message ?

C#
object objValue = cmd.ExecuteScaler();
if (objValue != DbNull.Value)
{
  userId = Convert.ToInt32(objValue);
}
 
Share this answer
 
Try:
userId = (int) cmd.ExecuteScalar();


But please, don't store passwords in plain text!
See here: Password Storage: How to do it.[^]
 
Share this answer
 
Don't use convert, use (int)cmd.ExecuteScalar(); https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar%28v=vs.110%29.aspx[^].

Make sure your table data type is really integer. In worse case, do dynamic cast to test it:
C#
int value = cmd.ExecuteScalar() as int;
if (value != null)
   // do something
else
   // indicate that something goes wrong,
   // for example, throw more informative exception
   // then the cast exception


By the way, Convert is rarely useful. For example, if the object is string (compile-time type), better use parse methods, such as int.Parse or int.TryParse.

—SA
 
Share this answer
 
v2

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



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