Check if the database must be saved when you close a C# form (with bound controls)

  • Thread starter Thread starter polocar
  • Start date Start date
P

polocar

Hi,
I'm writing a C# program that interfaces with a SQL Server 2005
database (I use Visual Studio 2005 Professional Edition as compiler).
I have defined the classical ADO.NET SqlDataAdapter, DataSet and
DataTable objects so that, once the database has been loaded with the
SqlDataAdapter Fill method, you work with the data off-line.
I would like to put a control in the Form OnClosing event handler
method: if there are some changes pending, there should be a MessageBox
that asks the user if he wants to save the changes; otherwise (no
changes pending), the Form closes without warnings.
The only way I have thought to do that is the following:

protected override void OnClosing(System.ComponentModel.CancelEventArgs
e)
{
Base.OnClosing(e);

DataRow[] adrChangedRows = dtTable.Select("", "",
DataViewRowState.Added |

DataViewRowState.ModifiedCurrent | DataViewRowState.Deleted);

if (drChangedRows.Length > 0)
{
DialogResult dlgChange = MessageBox.Show("The database has
changed; do you want to

save the changes?", "Warning",

MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning);

if (dlgChange == DialogResult.Yes)
daTable.Update(drChangedRows);
else if (dlgChange == DialogResult.No)
dtTable.RejectChanges(); // probably unuseful, but for clearness
else // if (dlgChange == DialogResult.Cancel)
e.Cancel = true;
}
}

Do you think there is a faster (and more elegant) way to do that?

Thank you very much
 
Hi,

There's no better place to prompt the user and cancel the operation than in
the Closing event, IMO.

But you might want to use one of the DataSet.HasChanges method overloads
instead of dtTable.Select(...).

Also, you may want to look into control validation events and properties to
prevent attempting to save incomplete or bad data.
 
Back
Top