0
votes

I am trying to update select rows of the datagrid/sql table with textbox values entered in by the user. The can be updated with the code below but the value entered into the first textbox, textBox1, is entered into every row/column. Imgur album for datagridview post update :

 private void button2_Click(object sender, EventArgs e)
    {
        SqlConnection connectiont = new SqlConnection("Data Source=DESKTOP-P3JSE1C;Initial Catalog=logins;Integrated Security=True");
            {
                connectiont.Open();
                SqlCommand update = new SqlCommand("UPDATE dbo.logins SET site = @site, username = @username, pword = @pword, email = @email", connectiont);
                    update.Parameters.AddWithValue("@site", textBox1.Text);
                    update.Parameters.AddWithValue("@username", textBox1.Text);
                    update.Parameters.AddWithValue("@pword", textBox1.Text);
                    update.Parameters.AddWithValue("@email", textBox1.Text);
                    update.ExecuteNonQuery();

  }



            clear();//method to clear textboxes on the form w/ datagridview

    }

enter image description here

1
You do not have a WHERE clause. Are you planning to update the whole table? - I hope not. - Gurwinder Singh
Also to add I hope this is just a sample when you used 'textBox1.Text' for everything cause unless you add an ID column or whatever then even with WHERE clause you'll still update everything with the value of 'textBox1.Text' - P. Pat
Possible duplicate of UPDATE from SELECT using SQL Server - Usman

1 Answers

1
votes

To update only particular rows, you have to specify some conditions to identify the row in the table(primary key will be the best option here). You can use WHERE clause to specify those conditions. Let me assume that you want to update user name password and other details for a particular site, so the condition here will be the value in the site column. in this case the query will be modified like the following:

SqlCommand update = new SqlCommand("UPDATE dbo.logins SET username = @username, pword = @pword, email = @email WHERE site = @site", connectiont);

update.Parameters.AddWithValue("@username", textBox1.Text);
update.Parameters.AddWithValue("@pword", textBox1.Text);
update.Parameters.AddWithValue("@email", textBox1.Text);
update.Parameters.AddWithValue("@site", textBox1.Text);

update.ExecuteNonQuery();

Now the code will update details for those rows in which the site coulms has the specified value. Keep in mind, saving password as plain text will not be a secured option, use proper encryption to make them secure.