用户名是不正确的错误我甚至不知道你有人帮助我

时间:2015-01-15 04:40:51

标签: c#

我一直得到一个用户名是不正确的错误这是登录我不知道为什么我desperatley需要帮助,我做了一切正确,但仍然给我错误我能做什么

下面是我的代码

protected void Button_Login_Click(object sender, EventArgs e)
{

    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegistrationConnectionString"].ConnectionString);
    conn.Open();
    string checkuser = "select count(*) from [Table] where UserName=@UserName";
    SqlCommand com = new SqlCommand(checkuser, conn);
    com.Parameters.Add("@UserName", SqlDbType.NChar, 20).Value = TextBoxUserName.Text + "'";
    int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
    //int temp = Convert.ToInt32(com.ExecuteScalar());
    conn.Close();
    if (temp == 1)
    {
        conn.Open();

        string checkPasswordQuery = " select password from [Table] where UserName=@UserName";
        SqlCommand passComm = new SqlCommand(checkPasswordQuery, conn);
        passComm.Parameters.Add("@UserName", SqlDbType.NVarChar, 20).Value = TextBoxUserName.Text;

        string password = passComm.ExecuteScalar().ToString().Replace(" ", "");

        if (password == TextBoxPassword.Text)
        {
            //declaring new session
            Session["New"] = TextBoxUserName.Text;
            Response.Write("PASSWORD IS CORRECT");

            Response.Redirect("Default.aspx");
        }
        else
        {
            Response.Write("PASSWORD IS NOT CORRECT");
        }
    }
    else
    {
        Response.Write("USERNAME IS NOT CORRECT");
    }
}

3 个答案:

答案 0 :(得分:1)

您无需在用户名末尾添加单引号。

替换它:

com.Parameters.Add("@UserName", SqlDbType.NChar, 20).Value = 
                                                TextBoxUserName.Text + "'";
                                                                      ^^^^^^

有了这个:

com.Parameters.Add("@UserName", SqlDbType.NChar, 20).Value = TextBoxUserName.Text;

答案 1 :(得分:0)

您还应修剪两个查询中的参数。

 string checkPasswordQuery = " select password from [Table] where Ltrim(Rtrim(UserName))=@UserName";
 SqlCommand passComm = new SqlCommand(checkPasswordQuery, conn);
 passComm.Parameters.Add("@UserName", SqlDbType.NVarChar, 20).Value = TextBoxUserName.Text.Trim();

答案 2 :(得分:0)

您的SQL查询区分大小写,可能是也可能不是。

您相信可以使用

“从[Table]中选择count(*),其中Lower(UserName)= Lower(@UserName)”

MDSN链接:http://msdn.microsoft.com/en-us/library/ms174400.aspx