I have a form which contains a DataGridView, a BindingSource, a DataTable, and a SqlDataAdapter. I populate the grid and data bindings as follows:
private BindingSource bindingSource = new BindingSource();
private DataTable table = new DataTable();
private SqlDataAdapter dataAdapter = new SqlDataAdapter("SELECT * FROM table ORDER BY id ASC;", ClassSql.SqlConn());
private void LoadData()
{
table.Clear();
dataGridView1.AutoGenerateColumns = false;
dataGridView1.DataSource = bindingSource;
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource.DataSource = table;
}
The user can then make changes to the data, and commit those changes or discard them by clicking either a save or cancel button, respectively.
private void btnSave_Click(object sender, EventArgs e)
{
// save everything to the displays table
dataAdapter.Update(table);
}
private void btnCancel_Click(object sender, EventArgs e)
{
// alert user if unsaved changes, otherwise close form
}
I would like to add a dialog if cancel is clicked that warns the user of unsaved changes, if unsaved changes exist.
Question:
How can I determine if the user has modified data in the DataGridView but not committed it to the database? Is there an easy way to compare the current DataGridView data to the last-retrieved query? (Note that there would not be any other threads or users altering data in SQL at the same time.)
In order to detect changes in the DataGridView, I wound up using two events, the CellValueChanged
and CurrentCellDirtyStateChanged
(the latter due to checkbox type columns).
When either of those events occurs, I set a boolean (UnsavedChanges) to indicate changes exist. When the form is closed or if the cancel button (now renamed to "Revert") is clicked, the boolean is checked and the dialog shown if set to true. If the save button is clicked, the boolean is set to false and the data saved.
While not as simple as checking one property of the databinding or datagrid, it works as desired.
This may be a dumb question but why wouldn't this work?
for VB
Dim changes As DataTable = table.GetChanges()
If changes.Rows.Count > 0 Then
MessageBox.Show("You have unsaved edits!")
End If
for C#
DataTable changes = table.GetChanges();
if (changes.Rows.Count > 0)
MessageBox.Show("You have unsaved edits!");
If your datatable is bound through a bindingsource to your datagridview then your recently modified but uncommitted edits are hanging out in your datatable. Datasets and datatables have a GetChanges()
method that can do the hard examination work and return to you exactly what was edited and nothing more and operate accordingly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With