Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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...)

like image 936
Thomas Avatar asked Dec 25 '12 15:12

Thomas


People also ask

How to add Rows in WPF DataGrid?

WPF DataGrid (SfDataGrid) provides built-in row called AddNewRow. It allows user to add a new row to underlying collection. You can enable or disable by setting SfDataGrid. AddNewRowPosition property.


1 Answers

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();                    
     }
like image 145
apomene Avatar answered Nov 04 '22 15:11

apomene