Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 378
Prisoner Avatar asked Feb 25 '11 18:02

Prisoner


People also ask

How to get selected row in DataGrid c#?

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.

How to show selected column in DataGridView c#?

Select the column value of DataGridView and show in another form in c# winform. Form2 frm = new Form2(); frm. ShowDialog();

How to select a particular cell in DataGridView c#?

CurrentCell = dataGridView1. Rows[rowindex]. Cells[columnindex].

How do I pass DataGridView selected row value to textbox in another form?

Text = Convert. ToString(frm. DataGridView1[1, row]. Value);


1 Answers

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"]; 
like image 200
Tony Abrams Avatar answered Oct 11 '22 05:10

Tony Abrams