Insert not working

Posted by user1642318 on Stack Overflow See other posts from Stack Overflow or by user1642318
Published on 2012-09-15T15:16:45Z Indexed on 2012/09/15 15:37 UTC
Read the original article Hit count: 193

Filed under:
|
|
|

I've searched evreywhere and tried all suggestions but still no luck when running the following code. Note that some code is commented out. Thats just me trying different things.

SqlConnection connection = new SqlConnection("Data Source=URB900-PC\SQLEXPRESS;Initial Catalog=usersSQL;Integrated Security=True");

        string password  = PasswordTextBox.Text;
        string email     = EmailTextBox.Text;
        string firstname = FirstNameTextBox.Text;
        string lastname  = SurnameTextBox.Text;

        //command.Parameters.AddWithValue("@UserName", username);
        //command.Parameters.AddWithValue("@Password", password);
        //command.Parameters.AddWithValue("@Email", email);
        //command.Parameters.AddWithValue("@FirstName", firstname);
        //command.Parameters.AddWithValue("@LastName", lastname);

        command.Parameters.Add("@UserName", SqlDbType.VarChar);
        command.Parameters["@UserName"].Value = username;

        command.Parameters.Add("@Password", SqlDbType.VarChar);
        command.Parameters["@Password"].Value = password;

        command.Parameters.Add("@Email", SqlDbType.VarChar);
        command.Parameters["@Email"].Value = email;

        command.Parameters.Add("@FirstName", SqlDbType.VarChar);
        command.Parameters["@FirstName"].Value = firstname;

        command.Parameters.Add("@LasttName", SqlDbType.VarChar);
        command.Parameters["@LasttName"].Value = lastname;

        SqlCommand command2 = new SqlCommand("INSERT INTO users (UserName, Password, UserEmail, FirstName, LastName)" +
        "values (@UserName, @Password, @Email, @FirstName, @LastName)", connection);

        connection.Open();
        command2.ExecuteNonQuery();
        //command2.ExecuteScalar();
        connection.Close();

When I run this, fill in the textboxes and hit the button I get......

Must declare the scalar variable "@UserName".

Any help would be greatly appreciated. Thanks.

© Stack Overflow or respective owner

Related posts about sql

Related posts about parameters