how to programatically delete mutiple selected rows in a datagridview?

H

Henry J.

Can somebody tell me how to delete multiple rows in a datagridview
selected by the user?

I tried the following two methods to no avail. I have a myDataGridView
that is bound to
myDataTable's myDataView. The column "Name" is the primary key.
I want to delete the rows selected by the user:

foreach (DataGridViewRow drv in myDataGridView.SelectedRows)
{
// this is not working, no error but does nothing
foreach (DataRowView drview in myDataView)
{
if (drview["Name"].Equals(drv.Cells["Name"]))
{
drview.Delete();
}
}

// nor is this working, same effect
foreach (DataRow dr in myDataTable.Rows)
{
if (dr["Name"].Equals(drv.Cells["Name"]))
{
dr.Delete();
}
}
}

I've searched through all the info I could, still could find anything.
Any help is
much appreciated!

Henry Jiang
 
H

Henry J.

I managed to delete some rows using:

myDataView.Sort = "Name";
int idx = myDataView.Find(drv.Cells["Name"].Value);
myDataView.Delete(idx);

However, the problem is that it is not always the selected rows that
are deleted,
especially if I sort the datagrid before I delete. In other words,
after myDataView
is sorted by "Name", the ordering is no longer what is shown in the
datagrid.
Some other rows may get deleted.

Now the question remains, how to link the selected rows in the UI to
the rows in
the DataView? DataView.Find can only find the rows if the DataView is
sorted...
 
H

Henry J.

solved by:

foreach (DataGridViewRow drv in
myDataGridView.SelectedRows)
{
myDataGridView.Rows.Remove(drv);
}

My oversight. Didn't look at .Rows.Remove().
 

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