title: Removing rows from a WPF datagrid
body: <p>I have a WPF <code>DataGrid theDataGrid</code> bound to a <code>DataSet ds</code> 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:</p>
  
  <pre><code>  DataSet ds = new DataSet();
          ...
    // fill ds somehow
          ...
    private void ButtonClickHandler(object Sender, RoutedEventArgs e) 
    {
          List&lt;DataRow&gt; theRows = new List&lt;DataRow&gt;();
          for (int i = 0; i &lt; 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();
          }
     }
  </code></pre>
  
  <p>Is there a better way to do this? E.g. one which needs only one loop and without having to check for the <code>NewItemPlaceHolder</code> explicitly, or possible a more efficient way to access the rows which are to be deleted?</p>
  
  <p>(I already figured out that I must not remove anything from the ds in the first loop, since then <code>theDataGrid.SelectedItems.Count</code> changes everytime the loop is executed...)</p>