Click here to Skip to main content
15,909,822 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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
C#
<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);
                //BindingSource bsource = new BindingSource();
                //bsource.DataSource = dbtable;

                dataGrid.ItemsSource = dbtable.DefaultView;
                oleda.Update(dbtable);
                int drow = dbtable.Rows.Count;
                int dcolumn = dbtable.Columns.Count;
                // System.Windows.MessageBox.Show(drow.ToString("G"));
                // System.Windows.MessageBox.Show(dcolumn.ToString("G"));
                //prepare the list of rows that need to delete
                List<DataRow> listOfRowsToDelete = new List<DataRow>();
                foreach (DataRowView drRow in this.dataGrid.SelectedItems)
                {
                    listOfRowsToDelete.Remove(drRow.Row);
                }
                //delete all the rows from the datatable
                foreach (DataRow drRow in listOfRowsToDelete)
                {
                    dbtable.Rows.Remove(drRow);
                }
                //  if (dataGrid != null)
                // {
                //   int selectedIndex = dataGrid.SelectedIndex;
                // dbtable.Rows.RemoveAt(selectedIndex);
                // bsource.RemoveAt(selectedIndex);
                //var row = dbtable.Rows[selectedIndex];
                //row.Delete();
                //oleda.Update(dbtable);

                // System.Windows.MessageBox.Show(selectedIndex.ToString("G"));

                // }
                //else
                //   {
                // if (dataGrid.SelectedItems.Count >= 1)
                //{
                //  while (dataGrid.SelectedCells.Count > 0)
                //{
                //     int selectedIndex = dataGrid.SelectedIndex;
                //    dbtable.Rows.RemoveAt(selectedIndex);
                // bsource.RemoveAt(selectedIndex);
                //    var row = dbtable.Rows[selectedIndex];
                //    row.Delete();
                //    oleda.Update(dbtable);
                //  }
                //}
                // }
            }
            catch (Exception ex)
            {
                System.Windows.MessageBox.Show(ex.Message);



            }
        }


XML
<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" />
Posted
Updated 16-Feb-19 8:54am
Comments
[no name] 16-Feb-19 14:11pm    
Loading, and then immediately expecting a proper "selected item", is not going to work.

Where is the "user" in this?
Priya Karthish 16-Feb-19 14:45pm    
My table named Author is getting loaded in the datagrid.Then I am selecting a row in the datagrid. Then I am trying to click a button to trigger the delete,but it's not getting deleted.
Richard Deeming 18-Feb-19 10:37am    
Because, as Gerry already explained, when you click the button, your are immediately re-binding the grid to the database.

When you re-bind the grid, the user's selection is lost. There are no selected rows to process.

1 solution

If you're going to use the DataGrid as a "selector" then you need to handle the "selected cell changed" or "selection changed" event.

You should also learn about "wait states" and event sequencing. Handling user input.

DataGrid.SelectedCellsChanged Event (System.Windows.Controls) | Microsoft Docs[^]

Selector.SelectionChanged Event (System.Windows.Controls.Primitives) | Microsoft Docs[^]
 
Share this answer
 
v2
Comments
Priya Karthish 16-Feb-19 15:41pm    
My Datagrid is already loaded with the contents from the Author Table when the Window is loaded. So SelectionChangedEvent is giving NullException Error.
An unhandled exception of type 'System.NullReferenceException' occurred in WpfApplication1.exe
Priya Karthish 18-Feb-19 11:58am    
Thanks. But I solved this problem by using commandbuilder GetDeletecommand() and updataing my datatable which is binded to datagrid. . It got deleted both from the datagrid and the database.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900