注册 asp.net 中类型 'System.Data.SqlClient.SqlException' 的异常

An exception of type 'System.Data.SqlClient.SqlException' in Registration asp.net

我正在尝试创建一个注册页面,但没有按计划进行。它不断抛出这个错误:

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code

在我的 table 我有

    [userid]          INT          NOT NULL,
    [username]        VARCHAR (50) NULL,

这是我的 C# 代码

 protected void Button1_Click(object sender, EventArgs e)
        {
            if (txtPassword.Text == txtConfirmPassword.Text)
            {
                string username = txtUsername.Text;
                string password = txtPassword.Text;
                string confirmpassword = txtConfirmPassword.Text;
                string email = txtEmail.Text;

                con.Open();
                String str = "INSERT INTO users (userid, username, password, confirmpassword, email) VALUES(@userid, @username, @password, @confirmpassword, @email)";

                SqlCommand cmd = new SqlCommand(str, con);

                cmd.Parameters.AddWithValue("@username", username);
                cmd.Parameters.AddWithValue("@password", password);
                cmd.Parameters.AddWithValue("@confirmpassword", confirmpassword);
                cmd.Parameters.AddWithValue("@email", email);

                cmd.ExecuteNonQuery();

                lblMessage.Text = "OK!!!!!!!!!!!!!!!!!!!";
                con.Close();
            }
        }

我不确定如何传递用户标识?

更新 需要将 IDENTITY 设置为数据库中的 userid。谢谢大家

您的代码尝试写入 5 个字段,但仅传递 4 个参数。
SqlCommand.Parameters 集合中缺少 @userid 参数。

现在有两种可能。如果您的 userid 字段是 IDENTITY 列,那么您不应该为 userid 字段传递任何内容,并且查询变为

  String str = @"INSERT INTO users (username, password, confirmpassword, email) 
                VALUES(@username, @password, @confirmpassword, @email)";

或者,如果它是一个普通字段,您需要将该参数添加到您的 SqlCommand 参数集合中。

首先;如果 isIdentity 设置为 true,则不要传递 userId 参数。 其次,即使它在您的连接字符串中提到,但您在查询中通过 CatalogName.dbo.TableName 调用您的 table。

"INSERT INTO dbName.dbo.users (username, password, confirmpassword, email) VALUES(@username, @password, @confirmpassword, @email)";