C# WPF:DataGrid,删除选定行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32424828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 13:23:38  来源:igfitidea点击:

C# WPF: DataGrid, Delete selected row

c#wpf

提问by Pop Pilli

I created a DataGrid which I linked to a DataBase (Table). 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。我的问题是如何从 DataGrid 中删除选定的行(使用 btn_click)并从数据库(表)中删除相同的数据。

Thanks in advance!

提前致谢!

回答by Martin

You can access the currently selected item of a DataGridusing the SelectedItemproperty.

您可以DataGrid使用该SelectedItem属性访问 a 的当前选定项。

Your can then call the Removemethod 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 (e.g. some Id) from the item in order to delete it in the database. Usually you cast the SelectedItemto the object you used to bind to the grid.

在第一行之后,您需要从项目中提取信息(例如某些 Id),以便在数据库中将其删除。通常,您将 投射SelectedItem到用于绑定到网格的对象。

See also thisresponse.

另请参阅回复。