34

我有一个简单DataTable的列,其中一列包含唯一值。例如:

ColumnName1   ColumnName2
value1        35
value2        44
value3        10

因为我知道值 1、2 和 3 总是彼此不同,所以我想仅使用ColumnName2和ColumnName1的值之一来获取该表的值。例如:

searchedValue = DataTable.Rows("value3").Item("ColumnName2) 
'result would be 10

我尝试了以下示例未成功:

4

4 回答 4

62
Dim rows() AS DataRow = DataTable.Select("ColumnName1 = 'value3'")
If rows.Count > 0 Then
     searchedValue = rows(0).Item("ColumnName2") 
End If

FirstOrDefault

Dim row AS DataRow = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault()
If Not row Is Nothing Then
     searchedValue = row.Item("ColumnName2") 
End If

在 C# 中:

var row = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault();
if (row != null)
     searchedValue = row["ColumnName2"];
于 2012-09-12T11:17:13.770 回答
2
'Create a class to hold the pair...

        Public Class ColumnValue
            Public ColumnName As String
            Public ColumnValue As New Object
        End Class

    'Build the pair...

        For Each row In [YourDataTable].Rows

              For Each item As DataColumn In row.Table.Columns
                Dim rowValue As New ColumnValue
                rowValue.ColumnName = item.Caption
                rowValue.ColumnValue = row.item(item.Ordinal)
                RowValues.Add(rowValue)
                rowValue = Nothing
              Next

        ' Now you can grab the value by the column name...

        Dim results = (From p In RowValues Where p.ColumnName = "MyColumn" Select  p.ColumnValue).FirstOrDefault    

        Next
于 2014-01-22T20:29:52.323 回答
-1
For i = 0 To dt.Rows.Count - 1

    ListV.Items.Add(dt.Rows(i).Item("STU_NUMBER").ToString)
    ListV.Items(i).SubItems.Add(dt.Rows(i).Item("FNAME").ToString & " " & dt.Rows(i).Item("MI").ToString & ". " & dt.Rows(i).Item("LNAME").ToString)
    ListV.Items(i).SubItems.Add(dt.Rows(i).Item("SEX").ToString)

Next
于 2020-09-06T06:04:47.710 回答
-4

尝试:

DataTable.Rows[RowNo].ItemArray[columnIndex].ToString()

(这是 C# 代码。将其更改为 VB 等效代码)

于 2012-09-12T11:22:44.640 回答