Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTable: How to get item value with row name and column name? (VB)

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.

like image 384
Nicolas Avatar asked Sep 12 '12 11:09

Nicolas


People also ask

What activity is used to get a column value from a specific row of a DataTable?

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.

What is DataRow in VB net?

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.


2 Answers

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"]; 
like image 63
Amiram Korach Avatar answered Oct 04 '22 13:10

Amiram Korach


'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 
like image 32
Stephen Craver Avatar answered Oct 04 '22 14:10

Stephen Craver