必须声明标量变量" @ UserId"在Insert语句中

时间:2014-12-01 19:28:41

标签: c#-5.0

我是绝对的初学者,我无法解决问题,得到错误&

正在抛出异常

objCommand.ExecuteNonQuery();

异常消息:" 必须声明标量变量@userId。"

         private void btnRegister_Click(object sender, EventArgs e)
    {
        if (tbxUserName.Text == "" || tbxPassword.Text == "")
        {
            MessageBox.Show("Please enter values!");
            return;
        }
        string strConnection;
        strConnection = ConfigurationManager.ConnectionStrings["strConnection"].ConnectionString;
        SqlConnection objConnection = new SqlConnection();
        objConnection.ConnectionString = strConnection;
        objConnection.Open();

        string strSQL;
        SqlCommand objCommand = new SqlCommand("SELECT * FROM LoginTable WHERE UserId='" + tbxUserName.Text + "';", objConnection);
        SqlDataAdapter objAdapter = new SqlDataAdapter();
        objAdapter.SelectCommand = objCommand;
        objAdapter.Fill(objDataSet);

        int i = objDataSet.Tables[0].Rows.Count;

        if (i > 0)
        {
            MessageBox.Show("User Name " + tbxUserName.Text + " already exists");
            tbxPassword.Text = "";
            objDataSet.Clear();
        }

        else
        {
            strSQL = "INSERT INTO LoginTable(UserId, Password) VALUES(@UserId, @Password)";          
            objCommand.Parameters.AddWithValue("@UsesrId", tbxUserName.Text);
            objCommand.Parameters.AddWithValue("@Password", tbxPassword.Text);

            objCommand.CommandText = strSQL;
            objCommand.ExecuteNonQuery();
            objConnection.Close();

            message = "Registered Successfully! " + "Welcome " + tbxUserName.Text;
            this.Hide();
            WelcomeForm wf = new WelcomeForm(message);
            wf.Show();

        }
    }

1 个答案:

答案 0 :(得分:0)

您的代码中有拼写错误,请将其更改为以下内容。(@ UssesrId!= @ UserId)

 strSQL = "INSERT INTO LoginTable(UserId, Password) VALUES(@UserId, @Password)";          
        objCommand.Parameters.AddWithValue("@UserId", tbxUserName.Text);