I have a simple DataTable
where one of the columns contains unique values. For example:
ColumnName1 ColumnName2 value1 35 value2 44 value3 10
Because I know that value 1, 2 and 3 will always be different one from another, I would like to get a value of this table only using ColumnName2 and one of the values of ColumnName1. That would for example be:
searchedValue = DataTable.Rows("value3").Item("ColumnName2) 'result would be 10
I tried the following examples unsuccessfully:
with the DataTable.Select method: returns an array of rows, but I only need one
with the DataTable.Rows.IndexOf method: if I understood well, I need to provide the whole row contents for it to be found with this method.
ColumnIndex - The index of the column whose value is to be retrieved from the DataRow. ColumnName - The name of the column whose value is to be retrieved from the DataRow.
By: Steven Holzner. DataRow objects represent rows in a DataTable object. You use DataRow objects to get access to, insert, delete, and update the records in a table.
Dim rows() AS DataRow = DataTable.Select("ColumnName1 = 'value3'") If rows.Count > 0 Then searchedValue = rows(0).Item("ColumnName2") End If
With FirstOrDefault
:
Dim row AS DataRow = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault() If Not row Is Nothing Then searchedValue = row.Item("ColumnName2") End If
In C#:
var row = DataTable.Select("ColumnName1 = 'value3'").FirstOrDefault(); if (row != null) searchedValue = row["ColumnName2"];
'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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With