views:

392

answers:

1

I have a DataGridView that's populated from a DataTableAdatper, as in this tutorial.

I guess since it's an ODBC MySQL connection, it's not generating DBDirectMethods for me.

My question is how do I update a specific row in the DB after the user has edited it in the grid? Do I need to specify a DeleteCommand in my adapter? When would it be called?

+1  A: 

You usually don't need to create the DeleteCommand, UpdateCommand and InsertCommand yourself : a CommandBuilder can do it for you :

private void UpdateCurrentRow()
{
    DataRowView drv = dataGridView1.CurrentRow.DataBoundItem as DataRowView;
    DataRow[] rowsToUpdate = new DataRow[] { drv.Row };

    OdbcDataAdapter adapter = new OdbcDataAdapter("SELECT * FROM FOO", connection);
    OdbcCommandBuilder builder = new OdbcCommandBuilder(adapter);
    adapter.Update(rowsToUpdate);
}
Thomas Levesque
But how do I tell it which rows to update? Can't the grid control do this? (i.e. decide which rows were modified, and call update for them?)
Assaf Lavie
The DataGridView updates its DataSource (i.e. the DataSet in your case), but it's your responsibility to update the database to reflect the changes in the DataSet. You can also call adapter.Update on the whole DataTable, only modified rows will be update in the database.
Thomas Levesque