I need to delete the selected row from the datagrid and also from the datatable. I tried this code, but it's not getting deleted.
datagrid.SelectedItems returns null. So it's not executing the Foreach loop
What I have tried:
Code to delete a row from datagrid and datatable
My Datagrid name is dataGrid
<pre>private void button_Click_1(object sender, RoutedEventArgs e)
{
string db = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source =C:\Users\Lavanya\Documents\BMDatabase.accdb;Persist Security Info=False";
OleDbConnection oledb = new OleDbConnection(db);
OleDbCommand olecmd = new OleDbCommand("Select * From ACTOR", oledb);
try
{
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = olecmd;
DataTable dbtable = new DataTable();
oleda.Fill(dbtable);
dataGrid.ItemsSource = dbtable.DefaultView;
oleda.Update(dbtable);
int drow = dbtable.Rows.Count;
int dcolumn = dbtable.Columns.Count;
List<DataRow> listOfRowsToDelete = new List<DataRow>();
foreach (DataRowView drRow in this.dataGrid.SelectedItems)
{
listOfRowsToDelete.Remove(drRow.Row);
}
foreach (DataRow drRow in listOfRowsToDelete)
{
dbtable.Rows.Remove(drRow);
}
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message);
}
}
<pre><DataGrid x:Name="dataGrid" ItemsSource="{Binding Properties}" SelectedItem="{Binding SelectedProperty,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Height="238" Margin="10,120,0,0" VerticalAlignment="Top" Width="733" />