简体   繁体   English

C#WPF:DataGrid,删除选定的行

[英]C# WPF: DataGrid, Delete selected row

I created a DataGrid which I linked to a DataBase (Table). 我创建了一个DataGrid,并将其链接到数据库(表)。 My question is how can I delete a selected row (using btn_click) from the DataGrid and also delete the same data from the DataBase (Table). 我的问题是如何从DataGrid中删除选定的行(使用btn_click),又如何从数据库(表)中删除相同的数据。

Thanks in advance! 提前致谢!

You can access the currently selected item of a DataGrid using the SelectedItem property. 您可以使用SelectedItem属性访问DataGrid的当前选定项目。

Your can then call the Remove method to remove the item from the DataGrid 然后,您可以调用Remove方法从DataGrid删除项目。

var selectedItem = myDataGrid.SelectedItem;
if (selectedItem != null)
{
   myDataGrid.Items.Remove(selectedItem);
}

After the first line you need to extract the information (eg some Id) from the item in order to delete it in the database. 在第一行之后,您需要从项目中提取信息(例如一些ID),以便在数据库中将其删除。 Usually you cast the SelectedItem to the object you used to bind to the grid. 通常,您将SelectedItem投射到用于绑定到网格的对象。

See also this response. 另请参阅响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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