'DataGrid return selectedItems only if row.Header is selected
I have a DataGrid and want to get the selected items and delete with right click option. When I select at least one cell of a row, it must delete the entire row.
When I select like in the example below:
the DataGrid.SelectedItems.Count is 0. However, if I include the row header in the selection, it works perfectly.
Does anyone have any clue about it?
Code:
private void DeleteRowSelection_Executed(object sender, System.Windows.Input.ExecutedRoutedEventArgs e)
{
DataTable dataTable = ((DataEditor)sender).DataNode.DataTable;
var gridCell = ((DataGridCell)e.OriginalSource);
var parent = VisualTreeHelper.GetParent(gridCell);
while (parent != null && parent.GetType() != typeof(DataGrid))
{
parent = VisualTreeHelper.GetParent(parent);
}
DataGrid dataGrid = (DataGrid)parent;
try
{
if (dataGrid.SelectedItems.Count == 1)
{
int selectedIndex = dataGrid.SelectedIndex;
var row = dataTable.Rows[selectedIndex];
row.Delete();
}
else if (dataGrid.SelectedItems.Count > 1)
{
while (dataGrid.SelectedItems.Count >= 1)
{
DataRowView drv = (DataRowView)dataGrid.SelectedItem;
drv.Row.Delete();
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
