简体   繁体   中英

Delete a specific row in Datagrid C# WPF

I am working with a simple application with c# What I wan't to do is that when I retrieve data from SQL Database into Datagrid, i want some of rows to deleting by selecting them and then clicking a button.

The code i used to retrieve data is shown below:

     SqlConnection conn = new SqlConnection("Server=MEO-PC;Database= autoser; Integrated Security = true");

        conn.Open();

        SqlCommand cmd = new SqlCommand("SELECT * From evidenc", conn);
        DataTable dt = new DataTable("dtList");
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        dtg.ItemsSource = dt.DefaultView;
        SqlDataAdapter adapt = new SqlDataAdapter(cmd);
        DataSet ds = new DataSet();
        adapt.Fill(ds);

        conn.Close();

Also the code i tried for deleting the specific row is:

     if (dtg.SelectedIndex >= 0)
        {
            dtg.Items.RemoveAt(dtg.SelectedIndex);
        }

The erro i get is :Operation is not valid while ItemsSource is in use. Access and modify elements with ItemsControl.ItemsSource instead.

I don't know where is the problem cause I'am new to programming. Thanks to everyone

You need to remove the row from the DataTable . Try this:

DataRowView drv = dtg.SelectedItem as DataRowView;
if(drv != null)
{
    DataView dataView = dtg.ItemsSource as DataView;
    dataView.Table.Rows.Remove(drv.Row);
}

You can't remove an item from the Items collection when you have set the ItemsSource property.

You can use IEditableCollectionView to do this. You can directly change the underlying collection, if it allows changes to be made, by using the methods and properties that IEditableCollectionView exposes, regardless of the collection's type.

IEditableCollectionView iecv = CollectionViewSource.GetDefaultView(theDataGrid.ItemsSource) as IEditableCollectionView;

 while (theDataGrid.SelectedIndex >= 0)
            {
                int selectedIndex = theDataGrid.SelectedIndex;
                DataGridRow dgr = theDataGrid.ItemContainerGenerator.ContainerFromIndex(selectedIndex) as DataGridRow;
                dgr.IsSelected = false;

                if (iecv.IsEditingItem)
                {
                    // Deleting during an edit!
                    iecv.CommitEdit();
                    iecv.RemoveAt(selectedIndex);
                }
                else
                {
                    iecv.RemoveAt(selectedIndex);
                }
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM