A problem with the automatic empty rows removal in DataGridView

N

nvx

Hello everyone,
there's a problem with a DataGridView and I'm not able to solve it...
:( I'm quite a newbie to C#, could anyone help me please?

I have a DataGridView bound to an Access database and a piece of code,
which should remove all the selected rows in the grid. The thing is
there are TWO empty rows after the removal in some cases... Then,
clicking on any cell in the grid or even on another control on the form
fires some (I don't know which) event and that subsequently causes the
DataGrid to remove one of the two empty rows at the end of the table.

I've found out that this behaviour could be influenced by the order in
which I'm selecting the rows. It is quite obvious that the uncommitted
new row at the end of the table might be among the selected rows as
well... When I do not select the uncommitted new row, the semifinal row
might be listed anywhere in the MyDataGridView.SelectedRows collection
and rows are removed correctly. Let's now assume the uncommitted new
row has been selected. With a simple statement I deselect the last row
to prevent an exception to be thrown while removing. Then there are two
possibilities: either the semifinal row is listed as the first object
in the MyDataGridView.SelectedRows collection or it is listed somewhere
else. In case it is listed as the first object, the undesired
two-empty-rows thing happens, otherwise the lines are removed correctly
and only one empty row is left at the end of the grid.

Here's the code:

// get the index of the last row
int last = MyDataGridView.Rows.Count - 1;
// deselect the uncommitted new row if it is selected
if (MyDataGridView.SelectedRows.Contains(MyDataGridView.Rows[last]))
{
MyDataGridView.Rows[last].Selected = false;
}
// remove selected rows
foreach (DataGridViewRow row in MyDataGridView.SelectedRows)
{
MyDataGridView.Rows.Remove(row);
}


Thank you for any help...

Regards

nvx
 

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