0

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

10
  • But it did not work because e.Row is a read-only property apparently. What exact exception was thrown? Commented Jul 6, 2017 at 11:09
  • you need to update the value in row_leave event Commented Jul 6, 2017 at 11:13
  • @njwills No exception thrown. But no change either. Commented Jul 6, 2017 at 11:33
  • @Krishna I want to store the DateTime when row is saved to database, not when a row loses focus Commented Jul 6, 2017 at 11:36
  • 1
    At what point you save it to database ? not on row leave ? do you have a button ? if so do it there Commented Jul 6, 2017 at 11:37

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.