Greetings, I took an existing code sample, added code to detect changes and then prompt for exit without saving or save and close.
It uses MS-Access but does not matter as all that matters is the DataTable in the DataSet.
Form code
using System;
using System.ComponentModel;
using System.Windows.Forms;
using Access1.Classes;
using static Access1.Classes.Dialogs;
namespace Access1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Closing += OnClosing;
}
private void OnClosing(object sender, CancelEventArgs e)
{
if (dataSet1.Tables[0].HasChanges())
{
if (Question("Save before exiting"))
{
SaveChanges();
}
else
{
e.Cancel = false;
}
}
}
private void personBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
SaveChanges();
}
private void SaveChanges()
{
Validate();
personBindingSource.EndEdit();
tableAdapterManager.UpdateAll(dataSet1);
}
private void Form1_Load(object sender, EventArgs e)
{
personTableAdapter.Fill(dataSet1.Person);
}
}
}
MessageBox
public static class Dialogs
{
public static bool Question(string text)
{
return (MessageBox.Show(
text,
Application.ProductName,
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2) == DialogResult.Yes);
}
}
Detect changes (can be optimize, wrote it fast)
public static class ExtensionMethods
{
public static bool HasChanges(this DataTable table)
{
var added = table.GetChanges(DataRowState.Added);
if (added != null)
{
return true;
}
var deleted = table.GetChanges(DataRowState.Deleted);
if (deleted != null)
{
return true;
}
var modified = table.GetChanges(DataRowState.Modified);
if (modified != null)
{
return true;
}
return false;
}
}