I\'m trying to delete a row from a DataGridView
I use two types of instuctions
A
VouchersDGV.Rows.Clear()
B
At the point of validation, it is relying on a particular state, and it obviously isn't happy for you to start changing the rows when it only asked you to validate something. I can't say I blame it; having to re-validate the scenario after every event would get... confusing; better to prevent the change.
You could instead queue the item for removal, on a timer of another callback, or maybe there is a mechanism for saying "no" during validation.
I have had the similar problem, my datagridview control was bound by dataBindingSource to BindingList of objects, and I was unable to remove a row from datagrid. The solution for me was remove an item from BindingList.
The RowValidating
event is fired after a user has changed a row's contents and then attempts to move to another row. The purpose of 'RowValidating' is to let you (the programmer) check the changes just made and cancel those changes and/or prevent the user from moving to a different row. It makes sense, then, that you are prohibited from deleting the current row (or any other row) inside this event handler.
I'm not exactly clear on what you're trying to accomplish here. The RowValidated
event (not RowValidating
) may work for your purposes instead.
Update: I think RowLeave
is actually the event you want to use, and if not you can try a different event from this list:
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview_events.aspx
I had the same problem. In my case I need to save changes when the user changes selection in DataGridView. I use RowValidating
event to check any changes and ask the user to save them. But when I tried to save changes inside this handler I got exception "Operation cannot be performed in this event handler."
I was needed an event that rises after RowValidating
and where I can save my changes. I didn't find such event. So I use timer for that. I start timer in RowValidating
event and save my data when timer ticks.
Here is my code:
private void timerForSaving_Tick(object sender, EventArgs e)
{
if (_saveChanges)
{
timerForSaving.Stop();
SaveData();
_saveChanges = false;
}
}
private void dataGridView1_RowValidating(object sender, DataGridViewCellCancelEventArgs e)
{
if (_hasUnsavedChanges)
{
DialogResult dr = MessageBox.Show("Do you want to save changes?", "Question",
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dr == DialogResult.Yes)
{
e.Cancel = true;
_saveChanges = true;
timerForSaving.Start();
}
}
}