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.
To get the selected rows in a DataGridView controlUse the SelectedRows property. To enable users to select rows, you must set the SelectionMode property to FullRowSelect or RowHeaderSelect.
Select the column value of DataGridView and show in another form in c# winform. Form2 frm = new Form2(); frm. ShowDialog();
CurrentCell = dataGridView1. Rows[rowindex]. Cells[columnindex].
Text = Convert. ToString(frm. DataGridView1[1, row]. Value);
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"];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With