user1523271
user1523271

Reputation: 1063

C# SQL DataGridView change field before updating database

I have a WindowsForms app with a DataGridView bound to a SQL database. All columns except one ("ts_last_edit") are editable. I want to update the "ts_last_edit" column only programmatically with the current DateTime every time someone changes some of the other columns AND saves the changes. I tried this:

...
    this.MyTableAdapter.Adapter.RowUpdating += Adapter_RowUpdating;
...
private void Adapter_RowUpdating(object sender, SqlRowUpdatingEventArgs e)
{
  e.Row["ts_last_edit"]=DateTime.Now;    
}

But it did not work because e.Row is a read-only property apparently.

I tried changing the UPDATE SQL command and it works:

private void Adapter_RowUpdating(object sender, SqlRowUpdatingEventArgs e)
{
// pseudo code
string newSqlCommand= "STUFF CURRENT DATE AND TIME IN COLUMN ts_last_edit";
e.Command.CommandText = newSqlCommand;
}

This works OK, but I was wondering if there is a better way to do it. Thank you

Upvotes: 0

Views: 55

Answers (1)

Krishna
Krishna

Reputation: 1985

you need to merge changes back to dataset after updating the time

private void brandBookBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
  this.Validate();
  var changes = dataSet1.GetChanges();
  if(changes!=null && changes.Tables["BrandBook"].Rows.Count>0)
  {
    foreach(row in changes.Tables["BrandBook"].Rows)
    {
      row["ts_last_edit"] = DateTime.Now;
    }
  }
  dataSet1.Merge(changes, false,System.Data.MissingSchemaAction.Add);
  this.brandBookBindingSource.EndEdit();
  this.tableAdapterManager.UpdateAll(this.dataSet1);
}

Upvotes: 2

Related Questions