With dataTable.GetChanges() you can get changes as a list. Iterating through them you can apply insert/update/delete operations. Here is a sample save button saving the changes to oracle db from DataGridView.
I implemented insert and update. You can simply implement delete too. Also note that I assumed the tables has first column as primary key for simplicity. You can alter the code to use it for multiple column pks. Table is dynamically selected from a ComboBox.
private void button_SaveToDb_Click(object sender, EventArgs e)
{
using (OracleConnection conn = new OracleConnection())
{
conn.ConnectionString = textBox_ConString.Text;
conn.Open();
var dataTable = (DataTable)dataGridView1.DataSource;
var changes = dataTable.GetChanges();
if (changes != null)
{
foreach (DataRow row in changes.Rows)
{
switch (row.RowState)
{
case DataRowState.Added:
OracleCommand command = new OracleCommand()
{
Connection = conn,
BindByName = true
};
var qry = $"INSERT INTO {comboBox_Tables.SelectedItem.ToString()} (";
StringBuilder sb = new StringBuilder();
int i = 0;
foreach (var col in row.Table.Columns)
{
sb.Append(col + ((i == row.Table.Columns.Count - 1) ? "" : ","));
command.Parameters.Add(new OracleParameter(col.ToString(), row.ItemArray[i]));
i = i + 1;
}
sb.Append(") VALUES (");
i = 0;
foreach (var col in row.Table.Columns)
{
sb.Append(":" + col + ((i == row.Table.Columns.Count - 1) ? "" : ","));
command.Parameters.Add(new OracleParameter(col.ToString(), row.ItemArray[i]));
i = i + 1;
}
sb.Append(")");
command.CommandText = qry + sb;
command.ExecuteNonQuery();
break;
case DataRowState.Deleted:
break;
case DataRowState.Modified:
command = new OracleCommand()
{
Connection = conn,
BindByName = true
};
qry = $"UPDATE {comboBox_Tables.SelectedItem.ToString()} SET ";
sb = new StringBuilder();
i = 0;
foreach (var col in row.Table.Columns)
{
if (i > 0)
{
sb.Append(col + "=:" + col + ((i == row.Table.Columns.Count - 1) ? "" : ","));
}
command.Parameters.Add(new OracleParameter(col.ToString(), row.ItemArray[i]));
i = i + 1;
}
command.CommandText = qry + sb + $" WHERE {row.Table.Columns[0]} = :{row.Table.Columns[0]}";
command.ExecuteNonQuery();
break;
}
}
((DataTable)dataGridView1.DataSource).AcceptChanges();
}
}
}