Dave Dave - 20 days ago 14
C# Question

c# wpf - DataGrid delete selected rows

I am using c #, wpf, DataGrid, SqlDataAdapter, DataTable, MS Sql server
On the main form there is a DataGrid and a button.
Clicking on the button should be removed from the DataGrid selected lines. And then from the database. But this is not happening! Only from the DataGrid!
Here is my code:

private void Button_DeleteSelectedRows_Click(object sender, RoutedEventArgs e)
{
try
{
if (dataGrid.SelectedItems.Count == 1)
{
int selectedIndex = dataGrid.SelectedIndex;
var row = dataTable.Rows[selectedIndex];
row.Delete();

dataAdapter.Update(dataTable);
}
else if (dataGrid.SelectedItems.Count > 1)
{
int count = dataGrid.SelectedItems.Count;

for (int i = count - 1; i >= 0; i--)
{
DataRowView rowView = dataGrid.SelectedItems[i] as DataRowView;

dataTable.AsEnumerable()
.Where(r => r["Name"].ToString() == rowView.Row["Name"].ToString())
.ToList()
.ForEach(r => r.Delete());
dataTable.AcceptChanges();
}
dataAdapter.Update(dataTable);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}


}

P.S.: I do not use MVVM

Thank you very much for the help!

Answer

You may consider refactoring the for-loop into a while loop., e.g while(datagrid.SelectedItem.Count >=1). Generally you will encounter issues when accessing an collection based on index, in case if you delete an item within a loop.

Debug Tip: Try to check count of selected Items within the for-loop loop and check if the object exists @ particular index.