Experts,
I`ve spent too much time to figure out a way to undo changes [Delete Row, Add Row, Edit Cells] in a DataGridView. I have context menu with an "Undo" option.
The DataSource for the DataGridView is a regular List object.
I`m using C# .NET 3.5 VS2008
//Conext Menu
//Edit Row Context Menu
private void EditRowCM_ItemClicked(obje
ct sender, ToolStripItemClickedEventA
rgs e)
switch (e.ClickedItem.Name)
case "AddRowTSMI":
AddMotRow();
break;
case "DeleteRowTSMI":
DeleteMotRow();
break;
case "DeleteSelectedTSMI":
DeleteSelected();
break;
case "UndoEditTSMI":
UndoEdit();
break;
default:
break;
private void DeleteRow()
if (this.GridView.SelectedRow
s.Count > 0)
if (this.GridView.SelectedRow
s[0].Index
== 0)
MessageBox.Show("Cannot edit the first Row");
else if (this.GridView.SelectedRow
s[0].Index
== this.GridView.Rows.Count - 1)
MessageBox.Show("Cannot edit the last Row");
this.GridView.Rows.RemoveA
t(this.Gri
dView.Sele
ctedRows[0
].Index);
MessageBox.Show("No Row Selected - Or Select the full Row");
private void DeleteSelected()
foreach (DataGridViewCell Cell in this.GridView.SelectedCell
s)
if (Cell.ColumnIndex == 0)
else if (Cell.RowIndex == 0)
else if (Cell.RowIndex == this.GridView.RowCount - 1)
Cell.Value = null;
private void UndoEdit()
//What goes in here?
One of the ideas I had was to create a temporary BindingSource which will hold all the information before the edit. When the user clicks the Undo contect menu, the temporary bindingsource becomes the source for the GridView, giving it the original information. Didn`t work!
Any guidance is greatly appreciated.
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.canceledit.aspx
You could have classes like this:
Open in new window
public BindingSource BSTemp = new BindingSource();
private void DeleteMotRow()
BSTemp = BS; //Make a Temp Binding Source before the Edit
//Code to Delete the rows
private void UndoEdit()
MotGridView.DataSource = null;
MotGridView.DataSource = BSTemp;
BS = BSTemp;