简体   繁体   English

VB.NET WPF如何从datagrid获取列值?

[英]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 因此,我对WPF不太熟悉,在WinForms中,您可以拥有CellDoubleClick事件,该事件可以得到如下值

row.Cells("ID").Value.ToString()

But in WPF, row is not a member of datagrid. 但是在WPF中,row不是datagrid的成员。 So how can I get the value of the selected ID if user just double click on the row? 那么,如果用户双击该行,如何获得所选ID的值? 在此处输入图片说明 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? 当显示多行记录,并且用户双击任一行时,如何获得所选行ID的值? To get the selectedIndex is easy but I am lost trying to figure out how do I get the value of the ID. 要获取selectedIndex很容易,但是我很想弄清楚如何获取ID的值。

-------UPDATE------- -------更新-------

So in WinForms , I would obtain the ID like this but not sure how in WPF. 因此,在WinForms中 ,我将获得像这样的ID,但不确定如何在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

In WPF data grids, the grid itself should never be used to acquire data. 在WPF数据网格中,永远不要将网格本身用于获取数据。 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. 选定的行索引或“ SelectedIndex ”是用于交叉引用绑定数据源的对象。

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: 例如,假设您有一些DataTable并将其视图绑定到DataGrid,则可能会有类似以下的内容:

    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. 如果您将DataTable的视图绑定到网格,那应该可以,但是请记住,网格可以采用任何IEnumerable。 So your question really depends heavily on what object is your ItemsSource, and how that object implements IEnumerable. 因此,您的问题实际上取决于您的ItemsSource是什么对象,以及该对象如何实现IEnumerable。

hope that helps! 希望有帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM