Skip to main content
 首页 » 编程设计

c#之如何确定哪个 DataRow 绑定(bind)到 DataGridViewRow

2024年02月24日17lovecherry

当我使用 DataTable作为DataGridView的 DataSource ,我经常需要找到用户选择了哪些行并从 DataTable 中读取特定值(不是 DataGridView)

我想知道是否有任何可靠的方法来确定哪个 DataRow一个DataGridViewRow尤其是当用户在默认顺序以外的列上对 DataGridView 进行排序时。

目前,我使用这种代码:

Dim sorting = "" 
 
If DataGrid.SortOrder <> SortOrder.None Then 
    'get the actual row if the results are sorted' 
    sorting = "[" & DataGrid.SortedColumn.Name & "]" &  
              If(DataGrid.SortOrder = SortOrder.Ascending, "", " DESC") 
End If 
 
'return the selected row after sorting' 
Dim selectedRowIndices = (From r In DataGrid.SelectedRows Select  
                          DirectCast(r, DataGridViewRow).Index).ToArray 
SelectedDataRow = (DataTable.Select("", sorting).Where( 
                   Function(r As DataRow, i As Integer) i = selectedRowIndex) 
                  ).FirstOrDefault 

谢谢。

请您参考如下方法:

DataGridViewRow.DataBoundItem 将为您提供 Databound 数据表(数据 View )中当前项目的 dataViewRow。

所以:

Dim drv as DataRowView = myDataGridViewRow.DataBoundItem 
 
Dim dr as DataRow = drv.Row 

将从您的数据 GridView 行中为您提供数据行。