Student Student - 10 months ago 92 Question

VB.NET WPF How to get the column value from datagrid?

So I am not quite familiar with WPF yet and in WinForms, you can have CellDoubleClick event which I can get the value like


But in WPF, row is not a member of datagrid. So how can I get the value of the selected ID if user just double click on the row?
enter image description here
Here is a picture to clarify my question. The record shown is from a datatable. When multiple row of records is shown, and the user double click on any of the row, how do I get the value of the selected row ID? To get the selectedIndex is easy but I am lost trying to figure out how do I get the value of the ID.


So in WinForms, I would obtain the ID like this but not sure how in WPF.

Private Sub DataGridView1_CellDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView1.CellDoubleClick
If e.RowIndex >= 0 Then
Dim row As New DataGridViewRow
row = Me.DataGridView1.Rows(e.RowIndex)
THE_ID = row.Cells("ID").Value.ToString() 'The ID is saved
End If
End Sub

Answer Source

In WPF data grids, the grid itself should never be used to acquire data. But instead, use the information you DO know about the grid. The selected row index, or "SelectedIndex" is what you should use to cross-reference your bound data source.

For example, let's assume that you had some DataTable and bound it's view to the DataGrid, you might have something that looks like this:

    Dim View As DataView = TryCast(DataGrid1.ItemsSource, DataView)
    If View IsNot Nothing Then
        Dim ViewRow As DataRowView = View.Item(DataGrid1.SelectedIndex)
        Dim ColumnValue As Object = ViewRow.Item("ID")  'or ViewRow.Item(0) for positional value.

        'do something with ColumnValue here.
    End If

That should work in the event that you are binding a DataTable's view to the grid, but remember the grid can take any IEnumerable. So your question really depends heavily on what object is your ItemsSource, and how that object implements IEnumerable.

hope that helps!