Your logic is correct, you can send the IDs and new owners of the selected rows to a stored procedure using a DataTable. Here is a step-by-step guide:
Add a CheckBox column to your DataGridView. This will allow the user to select rows that they want to update. You can add this column when you populate the DataGridView, or later on a button click event. Here's an example of how you might do this:
DataGridViewCheckBoxColumn checkBoxColumn = new DataGridViewCheckBoxColumn();
checkBoxColumn.HeaderText = "Update";
checkBoxColumn.Name = "checkBoxColumn";
dataGridView1.Columns.Insert(0, checkBoxColumn);
Create a DataTable and add the selected rows to it. When the user clicks the "Update" button, you can iterate over the rows of the DataGridView, check if the checkbox is checked, and if so, add the ID and new owner to the DataTable. Here's an example:
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Owner", typeof(string));
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (Convert.ToBoolean(row.Cells["checkBoxColumn"].Value))
{
dt.Rows.Add(row.Cells["ID"].Value, "New Owner");
}
}
Replace "ID" with the actual name of your ID column, and replace "New Owner" with the new owner that you want to set for the selected rows.
Pass the DataTable to a stored procedure. You can pass the DataTable to a stored procedure in SQL Server using a table-valued parameter, as I described in the previous answer. Here's an example:
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("UpdateOwner", conn))
{
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = cmd.Parameters.AddWithValue("@data", dt);
param.SqlDbType = SqlDbType.Structured;
param.TypeName = "dbo.MyTableType";
cmd.ExecuteNonQuery();
}
}
In this example, "UpdateOwner" is the name of your stored procedure, and "dbo.MyTableType" is a table type that you've defined in SQL Server with columns that match the structure of your DataTable.
Update the rows in SQL Server. Your stored procedure can use the table-valued parameter to update the rows in your table. Here's an example of how you might do this:
CREATE PROCEDURE UpdateOwner
@data dbo.MyTableType READONLY
AS
BEGIN
UPDATE MyTable
SET Owner = newData.Owner
FROM MyTable
JOIN @data newData ON MyTable.ID = newData.ID;
END
In this example, "MyTable" is the name of your table, and "dbo.MyTableType" is the table type that matches the structure of your DataTable. Replace these with your actual table and type names.
Remember to replace the placeholders in the above examples with the actual names from your project.