StudentDev StudentDev - 26 days ago 11
SQL Question

C# change cell value of selected datagridview rows in database

Hello i want to change the column of all the selected rows in datagridview and database but it is changing all of the data not just the selected rows.

This is how a populate the datagridview.

private void dgvAuditAllSettings()
{
crud.FillDataGrid("Select AuditID,DateTime,Name,Position,Action,Status from AuditTrail where Status = 'Active' order by DateTime DESC", ref dgvAuditAll);
dgvAuditAll.Columns[0].Width = 60;
dgvAuditAll.Columns[1].Width = 200;
dgvAuditAll.Columns[2].Width = 150;
dgvAuditAll.Columns[3].Width = 140;
dgvAuditAll.Columns[4].Width = 470;
}


and how i want to change its Column value. But it is changing all of the row in database not just the selected row.

private void btnAuditSendArchives_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dgvAuditAll.SelectedRows)
{
// row.Cells[5].Value = "Archived";
crud.AddRecord("Update AuditTrail set Status = 'Archive'");
}
}

Answer Source

You are indeed changing all rows in DB with this line:

crud.AddRecord("Update AuditTrail set Status = 'Archive'");

You didn't specify the id of the line, there is no where clause, so it will update all rows.

Try adding the id, it should be something like this:

crud.AddRecord($"Update AuditTrail set Status = 'Archive' Where AuditID = {row.Cells[0]}");

I use row.Cells[0] but it might be different depending on your implementation.