Hi!
I found trouble when I was about to delete multiple records from a DataGridView that is databound to a collection class.
If I haven't sorted the DataGridView it all works fine and as expected, but ones I've sorted the data by clicking one of the column headers it doesn't quite work. When I debug I can see that after the first delete action the underlying code seems to start reloding the data from my collection into the DataGridView control and thus breaking the chain of events fired by the initial delete action.
I have tried to find a way around this and guess that one way would be to not perform the actual entity.Delete() in the delete event chain fired by the DataGridView control, but instead collect info and wait until all those events have come to an end before persisting. This way however, I would find myself in a cumbersome situation if any of those deletes causes an error. I would have to store the way the DataGridView was sorted and reload the data from SQL to restore the current situation.
Before doing these modifications to my code I just want to know if I'm missing something. Is there a better way? Can I pause the reloding of the sorted DataGridView by queuing what I think is binding events fired from the collection? Or...?
These are the two events that I use to delete multiple records in the UNSORTED DataGridView control that works just fine (but mal functions when sorted).
private void OnUserDeletingRowPersonsDataGridView(object sender, DataGridViewRowCancelEventArgs deleteRowEventArgs)
{
if (!m_IsDeleting && !m_HasCancelledDeleting)
{
m_DeleteCount = m_PersonsDataGridView.Rows.GetRowCount(DataGridViewElementStates.Selected);
DialogResult deleteAnswer = MessageBox.Show(Utility.FormatString(LanguagesBusiness.GetTranslatedMessage("AreYouSureYouWantToDeleteRecords"), m_DeleteCount.ToString()), "", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1);
if (deleteAnswer == DialogResult.Yes)
{
m_IsDeleting = true;
}
else
{
deleteRowEventArgs.Cancel = true;
m_HasCancelledDeleting = true;
}
}
if(m_HasCancelledDeleting)
{
deleteRowEventArgs.Cancel = true;
m_DeleteCount--;
}
if (m_IsDeleting)
{
PersonsEntity person = (PersonsEntity)deleteRowEventArgs.Row.DataBoundItem;
if (!person.Delete())
{
MessageBox.Show(Utility.FormatString(LanguagesBusiness.GetTranslatedMessage("FailedToDeletePerson"), person.FullName), "", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
deleteRowEventArgs.Cancel = true;
m_HasCancelledDeleting = true;
m_DeleteCount--;
}
}
}
private void OnUserDeletedRowPersonsDataGridView(object sender, DataGridViewRowEventArgs e)
{
m_DeleteCount--;
if (m_DeleteCount == 0)
{
m_IsDeleting = false;
m_HasCancelledDeleting = false;
}
}