DataGridView - UserDeletingRow and UserDeletedRow (Bug???)

G

Guest

I have a dilemma when trying to delete a row from the DataGridView. Here
is a sample of my code:

private void dgv_EQUPS_UserDeletingRow(object sender,
DataGridViewRowCancelEventArgs e)
{
fDeleteRow = false;

if (chx_DeleteFlag.Checked)
{
DialogResult Ans = MessageBox.Show("Do you want to delete
this Row?", "Delete Row",
MessageBoxButtons.YesNo,
MessageBoxIcon.Question,
MessageBoxDefaultButton.Button2);

if (Ans == DialogResult.Yes)
{
fDeleteRow = true;
e.Cancel = false;
}
else
{
e.Cancel = true;
}
}
else
{
e.Cancel = true;
}

chx_DeleteFlag.Checked = false;

}

private void dgv_EQUPS_UserDeletedRow(object sender,
DataGridViewRowEventArgs e)
{

if (fDeleteRow)
{
try
{
sql_DA_EQUPS.Update(dsEQUPS, dsEQUPS.EQU_PS.TableName);
}
catch (System.Data.SqlClient.SqlException ex)
{
MessageBox.Show(ex.Message);
}
fDeleteRow = false;
}

}

Here how my code work…
Delete will only work if the chx_DeleteFlag checkbox is checked off.
When a Delete key is pressed on one of the rows in the DataGridView, it
generates a UserDeletingRow Event (dgv_EQUPS_UserDeletingRow) and ask a
question whether or not to Proceed. If Yes, then the fDeleteRow is set (I
used this as a safety value even though it is not needed) and also set the
e.Cancel Flag to false. From this, it will cause another event to be
generated called UserDeletedRow (dgv_EQUPS_UserDeletedRow) which I used to
update the SQL Database Table. As simple as this is, it works great when
dealing with multiple rows of data in the DataGridView.

Here’s the problem…
If there there is only one row of data left in the DataGridView and you try
to delete it, it does not generate the UserDeletedRow event and thus my SQL
Table is not updated. When the DataGridView is refreshed, that data still
exist. Just to verify, I checked the table in the SQL Database and found
that data is still there.

Here’s another problem…
I removed the UserDeletedRow and replaced it with RowsRemoved (this is
where the fDeleteRow flag comes in handy):

private void dgv_EQUPS_RowsRemoved(object sender,
DataGridViewRowsRemovedEventArgs e)
{
if (fDeleteRow)
{
try
{
sql_DA_EQUPS.Update(dsEQUPS, dsEQUPS.EQU_PS.TableName);
}
catch (System.Data.SqlClient.SqlException ex)
{
MessageBox.Show(ex.Message);
}
fDeleteRow = false;
}
}

This works great with single or multiple rows of data in the DataGridView
but I end up with a NullReferenceException. When I debugged this, the
NullReferenceException message goes away if I commented out the
sql_DA_EQUPS.Update statement.

I am verfy much stuck and haven’t found any reason why I cannot delete the
one remaining row in the DataGridView.

Any help would be great.

Thanks … Terry
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top