Thomas
Thomas

Reputation: 1160

Removing rows from a WPF datagrid

I have a WPF DataGrid theDataGrid bound to a DataSet ds containing a table. I want to enable the user to remove lines by first selecting them in the grid and then pressing a button (positioned somwhere outside of the datagrid). I finally arrived at the following lines of code which do what I want, but which I consider rather ugly:

  DataSet ds = new DataSet();
        ...
  // fill ds somehow
        ...
  private void ButtonClickHandler(object Sender, RoutedEventArgs e) 
  {
        List<DataRow> theRows = new List<DataRow>();
        for (int i = 0; i < theDataGrid.SelectedItems.Count; ++i)
        {
            // o is only introduced to be able to inspect it during debugging
            Object o = theDataGrid.SelectedItems[i];
            if (o != CollectionView.NewItemPlaceholder)
            {
                DataRowView r = (DataRowView)o;
                theRows.Add(r.Row);
            }
        }
        foreach(DataRow r in theRows) 
        {                
            int k = ds.Tables["producer"].Rows.IndexOf(r);
            // don't remove() but delete() cause of update later on
            ds.Tables[0].Rows[k].Delete();
        }
   }

Is there a better way to do this? E.g. one which needs only one loop and without having to check for the NewItemPlaceHolder explicitly, or possible a more efficient way to access the rows which are to be deleted?

(I already figured out that I must not remove anything from the ds in the first loop, since then theDataGrid.SelectedItems.Count changes everytime the loop is executed...)

Upvotes: 6

Views: 13619

Answers (3)

apomene
apomene

Reputation: 14389

In order to remove row selected on button click you can try:

private void ButtonClickHandler(object sender, RoutedEventArgs e)//Remove row selected
     {
      DataRowView dataRow = (DataRowView)dataGridCodes.SelectedItem; //dataRow holds the selection
      dataRow.Delete();                    
     }

Upvotes: 2

John B
John B

Reputation: 1

You can remove the double loop by iterating backwards :

private void ButtonClickHandler(object Sender, RoutedEventArgs e) {
    for (int i = theDataGrid.SelectedItems.Count-1; i>=0; --i)
        if (theDataGrid.SelectedItems[i] != CollectionView.NewItemPlaceholder)
            ds.Tables[0].Rows[i].Delete();
   }

Upvotes: 0

Ramin
Ramin

Reputation: 2133

I think it works by just one loop:

int count=theDataGrid.SelectedItems.Count;
int removedCount=0; 
while (removedCount < count)
{
    try{
         Object o = theDataGrid.SelectedItems[0];
    }
    catch{ break;}

    if (o == CollectionView.NewItemPlaceholder)
    continue;

    DataRowView r = (DataRowView)o;
    r.Row.Delete();
    removedCount++;
}

Upvotes: 0

Related Questions