C # database problem


Could somebody tell me why this isn't adding the values to the database. The form runs fine and doesn't return any errors.

    private void button1_Click(object sender, EventArgs e)
        SqlConnection connection = new SqlConnection();
        SqlCommand command = new SqlCommand();

        connection.ConnectionString = (@"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\John\Documents\Setup.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");

        command.Parameters.AddWithValue("@userName", textBox1.Text);
        command.Parameters.AddWithValue("@passWord", textBox2.Text);
        command.CommandText = "INSERT INTO Setup (userName, password) VALUES(@userName, @passWord)";

            int rowsAffected = command.ExecuteNonQuery();

        catch (Exception ex)
            // handle exception


FYI: I'm a "newbie" My database is called Setup. I've manually added a table called myTable with 2 columns of userName and another one called password both set at nchar(50)

You need to specify the Table, not the database (which gets used in the connection string). Added the schema prefix to the table name:

command.CommandText = "INSERT INTO dbo.myTable (userName, password) VALUES (@userName, @passWord)";

And add:

command.Connection = connection;

to associate your Command object with the connection object.