Reputation: 1971
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 contain 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.
Upvotes: 4
Views: 23402
Reputation: 1
This worked for me...
if (DataGrid1.SelectedItem != null)
{
DataRowView(DataGrid1.SelectedItem).Row.Delete();
}
Upvotes: 0
Reputation: 1
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();
}
Upvotes: 0
Reputation: 11
Do While dgData.SelectedItems.Count > 0
dgData.SelectedItem.Row.Delete()
Loop
Upvotes: 0
Reputation: 11
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.
Upvotes: 0
Reputation: 51
This also worked well for me.
while (dataGrid1.SelectedItems.Count > 0){
dataGrid1_item_source.Rows.RemoveAt(dataGrid1.SelectedIndex);
}
Upvotes: 4
Reputation: 5160
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);
}
Upvotes: 0
Reputation: 85
This worked for me...
while (dataGrid1.SelectedItems.Count > 0){
dataGrid1_item_source.Rows.RemoveAt(dataGrid1.SelectedIndex);
}
Upvotes: 0
Reputation: 1205
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;
Upvotes: 1
Reputation: 3681
By removing selected item you are changing SelectedItems
collection. You should copy it first and then start removing.
Upvotes: 6