开发者

WPF DataGrid Remove SelectedItems

Recently I've been working on a project which imports data programmicaly into a WPF DataGrid.

I'm almost done with the project but the thing that I left out was a button to remove selected cells and this is where I'm stuck!

I wrote this code using my basic knowledge of DataGrids:

var grid = dataGrid1;
if (grid.SelectedIndex >= 0)
 {
   for (int i = 0; i <= grid.SelectedItems.Count; i++)
   {
      grid.Items.Remove(grid.SelectedItems[i]);
   };
 }

Works fine on removing only the item selected just like CurrentItem but it doesn't remove anymore than 2 selected items!

The DataGrid I have should at least conta开发者_如何学Pythonin a minimum of 100 items. I've added a remove all option but this is also necessary.

I'll be thankful if anyone gives me the solution.


By removing selected item you are changing SelectedItems collection. You should copy it first and then start removing.


This also worked well for me.

while (dataGrid1.SelectedItems.Count > 0){
  dataGrid1_item_source.Rows.RemoveAt(dataGrid1.SelectedIndex);
}


The mistake you are doing here you are removing items during loop whaich is messing with loop count so make a copy grid and remove selecteditem from it and then equlize it by the orignal one.. Check this out

var grid = dataGrid1;
var mygrid = dataGrid1
if (grid.SelectedIndex >= 0)
{
  for (int i = 0; i <= grid.SelectedItems.Count; i++)
  {
    mygrid .Items.Remove(grid.SelectedItems[i]);  
   };
}

grid = mygrid;


This worked for me...

while (dataGrid1.SelectedItems.Count > 0){
  dataGrid1_item_source.Rows.RemoveAt(dataGrid1.SelectedIndex);
}


This worked for me...

if (DataGrid1.SelectedItem != null)
        {
            ((DataRowView)(DataGrid1.SelectedItem)).Row.Delete();
        }


A while loop using the SelectedItem instead of the SelectedIndex

while (dataGrid1.SelectedItems.Count > 0){
  if (dataGrid1.SelectedItem == CollectionView.NewItemPlaceholder)
      dataGrid1.SelectedItems.Remove(grid.SelectedItem);
  else
      dataGrid1.Items.Remove(dataGrid1.SelectedItem);
}


I have stack with the same problem as an author. And found quite beautiful (I think) solution.

And so the main problem is that the SelectedItems dynamic, and when you delete one row, it is recalculated again.

And so my code looks like this:

for (int i = -datagrid1.SelectedItems.Count; i < datagrid1.SelectedItems.Count; i++)
        {
            datagrid1.SelectedItems.RemoveAt(datagrid1.SelectedIndex);
        }

So, every time the for loop is doing step 1, datagrid1.SelectedItems.Count is decreased by 1, and the variable i increases.


Do While dgData.SelectedItems.Count > 0
 dgData.SelectedItem.Row.Delete()
Loop


My solution (if you are using adonet with autogeneratecolumns=true);

for (int i = dgv.SelectedItems.Count-1; i >= 0; i--)
{
     DataRowView dataRow = (DataRowView)dgv.SelectedItems[i];
     dataRow.Delete();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜