When using a DataGrid in WPF, you need to convert its SelectedItem to DataRowView
However SelectedItem and selecteditems the selectionunit and SelectionMode of the DataGrid Two properties are changed when the values are different
One: when datagrid.selectionunit = = Datagridselectionunit.fullrow, get the method of selecting one row and multiple lines:
1 Select multiple rows
int count = DataGrid.SelectedItems.Count;
datarowview[] drv = new Datarowview[count];
For (int i = 0; i < count; i++)
{
Drv[i] = datagrid.selecteditems[i] as DataRowView;
}
return DRV;
2 Select a row
Datagrid.selecteditem as DataRowView
Two: But when the Datagrid.selectionunit property is cell or Cellorrowheader, and the value of SelectionMode is extented, this is not a good deal. Because if the cell is selected, the value of SelectedItem is null. So it can be handled uniformly by cell, regardless of the value of the selectionunit, there is always a selected cell, and the row is determined by the cell.
Private DataRowView Getselectedrow ()
{
/ * Optimization
* Regardless of the DataGrid selectionunit and SelectionMode two attributes take any value
* All the selected cells exist
* Can be processed according to the selected cell, get the selected row
* Getselectedrows () method gets the same principle as selected multiline
*/
if (DataGrid! = null && DataGrid.SelectedCells.Count! = 0)
{
//When only one cell is selected: Returns the row in which the cell is located
When multiple is selected: Returns the row of the first cell
return datagrid.selectedcells[0]. Item as DataRowView;
}
return null;
}
<summary>
Private method Gets the selected multiline
</summary>
// <returns></returns>
Private datarowview[] getselectedrows ()
{
when there are multiple cells in the selected cell, get an array of rows
//Exclude the same rows in the array
if (datagrid!=null&&datagrid.selectedcells.count > 0)
{
datarowview[] dv = new Datarowview[datagrid.selectedcells.count];
For (int i = 0; i < DataGrid.SelectedCells.Count; i++)
{
Dv[i] = datagrid.selectedcells[i]. Item as DataRowView;
}
Because the selected cells may be in the same row, you need to exclude duplicate rows
return DV. Distinct (). ToArray ();
}
return null;
}
WPF DataGrid Gets the selected row or rows