Reputation: 45
I am attempting at creating a registration page but it's not going as planned. It keeps throwing this error:
An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
In my table I have,
[userid] INT NOT NULL,
[username] VARCHAR (50) NULL,
This is my c# code
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();
}
}
I am unsure of how to pass the userid?
Update Needed to set IDENTITY to userid in database. Thanks all
Upvotes: 0
Views: 1703
Reputation: 216293
Your code tries to write 5 fields but pass only 4 parameters.
The @userid
parameter is missing from the SqlCommand.Parameters collection.
Now there are two possibilities. If your userid field is an IDENTITY column then you shouldn't pass anything for the userid
field and the query becomes
String str = @"INSERT INTO users (username, password, confirmpassword, email)
VALUES(@username, @password, @confirmpassword, @email)";
or, if it is a normal field, you need to add that parameter to your SqlCommand parameter collection.
Upvotes: 3
Reputation: 1235
First of all; if isIdentity is set to true do not pass the userId param.
Second, even it is mentioned in your connectionstring but you call your table by CatalogName.dbo.TableName
in your query.
"INSERT INTO dbName.dbo.users (username, password, confirmpassword, email) VALUES(@username, @password, @confirmpassword, @email)";
Upvotes: 1