DataGrid get selected rows' column values
I'm trying to get the values of each column of a selected row in a DataGrid. This is what I have:
private void dataGrid1_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
DataGrid dg = sender as DataGrid;
Console.WriteLine(dg.SelectedCells[0].ToString());
}
But this does not work. If I do a SelectedCells.Count
then I get the correct number of columns but I cannot seem to actually get the values of these columns in the selected row. I've tried for quite a while with no luck! Here is my XAML:
<Grid>
<DataGrid CanUserAddRows="True" AutoGenerateColumns="False" Height="200" HorizontalAlignment="Stretch" Margin="12,12,79,0" Name="dataGrid1" VerticalAlignment="Top" Width="389" DataContext="{Binding}" CanUserResizeColumns="False" CanUserResizeRows="False" HorizontalContentAlignment="Stretch" PreviewMouseDoubleClick="dataGrid1_PreviewMouseDoubleClick" CellEditEnding="dataGrid1_CellEditEnding">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Path=UserID}"
Header="User ID" Width="SizeToHeader" />
<DataGridTextColumn Binding="{Binding Path=UserName}"
Header="User ID" Width="SizeToHeader" />
</DataGrid.Columns>
</DataGrid>
</Grid>
I would ideally like to access the data through doing something like rowData.UserID
but I cannot seem to work it out. There are lots of tutorials and help for using DataGridView but I'm not using this.
UPDATED
To get the selected rows try:
IList rows = dg.SelectedItems;
You should then be able to get to the column value from a row item.
OR
DataRowView row = (DataRowView)dg.SelectedItems[0];
Then:
row["ColumnName"];
Solution based on Tonys answer:
DataGrid dg = sender as DataGrid;
User row = (User)dg.SelectedItems[0];
Console.WriteLine(row.UserID);