Hi alladeen88,
If we use a
BindingList, we do not need to implement the
ICancelAddNew interface, BindingList already implements ICancelAddNew. We can check whether a row has uncommited changes via the
IsCurrentRowDirty property.
Based on my understanding, we can create a custom BindingList to simplify the cancel new logic. This is a sample:
//The item object, you can change this to your object.
public class DataSample
{
public int Id { set; get; }
public string Name { set; get; }
}
//Custom binding list.
public class MyBindingList : BindingList<DataSample>
{
//The index of the new row.
private int _newRowIndex = -1;
protected override object AddNewCore()
{
object newItem = base.AddNewCore();
//Save the new row index.
_newRowIndex = this.Count - 1;
return newItem;
}
public void CancelNew()
{
//Cancel adding if a new row is added.
if (_newRowIndex != -1)
base.CancelNew(_newRowIndex);
}
//Used to check if a new row is added.
public bool HasNewRow
{
get { return _newRowIndex != -1; }
}
}
This is the code snippet in the main form:
private void DGVCancelAddingForm_Load(object sender, EventArgs e)
{
//Disallow new row to be inserted by users.
this.dataGridView1.AllowUserToAddRows = false;
//Bind the bind list.
this.dataGridView1.DataSource = GetBindingList();
//Have the form be able to retrieve key when some controls got focus.
this.KeyPreview = true;
//Handle this event to deleted the new row by pressing Escape.
this.KeyUp += new KeyEventHandler(DGVCancelAddingForm_KeyUp);
}
void DGVCancelAddingForm_KeyUp(object sender, KeyEventArgs e)
{
MyBindingList list = this.dataGridView1.DataSource as MyBindingList;
if (e.KeyCode == Keys.Escape && list.HasNewRow && this.dataGridView1.IsCurrentRowDirty)
{
//cancel new row adding if a new row is added and the current row has values uncommited.
list.CancelNew();
}
}
private void buttonAdd_Click(object sender, EventArgs e)
{
//Click button1 to add a new item.
IBindingList list = this.dataGridView1.DataSource as IBindingList;
list.AddNew();
}
Let me know if this helps or not.
Aland Li
Please mark the replies as answers if they help and unmark if they don't. This can be beneficial to other community members reading the thread.