HelpASisterOut
HelpASisterOut

Reputation: 3185

Select with condition from a datatable in VB.net

I want to select a certain field from a datatable in VB based on the value of another field in the same row.

In SQL, it would easily be done by writing this query:

select error_message from table_errors where error_case="condition"

How do I do this if I have my SQL table filled in a datatable in VB? How do I select the item("error_message") in the datatable based on the item("error_Case") field?

Any help would be appreciated

Upvotes: 2

Views: 13890

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460138

You can use Linq-To-DataSet:

Dim matchingRows As IEnumerable(Of DataRow) = 
    From row In table
    Where row.Field(Of String)("error_case") = "condition"

If you just want one column (of course that works also in one step):

Dim errorMessages As IEnumerable(Of String) = 
    From row In matchingRows 
    Select row.Field(Of String)("error_message")

For Each error In errorMessages 
    Console.WriteLine(error)
Next 

If you expect it to be just a single row use First or Single(throws an exception if there is more than one row):

Dim error As String = errorMessages.First()

Since First throws an exception if the sequence is empty you can use FirstOrDefault:

Dim error As String = errorMessages.FirstOrDefault() ' is null/Nothing in case of an empty sequence 

All in one line (note that both Linq and DataTable.Select needs to use loops):

Dim ErrMessage As String = errorTable.AsEnumerable().
    Where(Function(r) r.Field(Of String)("Error_Case") = TextCase.Text).
    Select(Function(r) r.Field(Of String)("Error_Message")).
    FirstOrDefault()

Upvotes: 3

Catalin
Catalin

Reputation: 561

here is a worker version of the rough code

    Dim connString As String = "select error_message from table_errors where error_case='condition'"
    Dim conn As SqlClient.SqlConnection = New SqlClient.SqlConnection(connString)
    conn.Open()
    Dim cmd As SqlClient.SqlCommand = New SqlClient.SqlCommand(connString, conn)
    Dim dTable As DataTable = New DataTable()
    Dim dAdapter As SqlClient.SqlDataAdapter = New SqlClient.SqlDataAdapter(cmd)
    dAdapter.Fill(dTable)
    conn.Close()
    Dim text As String
    Dim dReader As DataTableReader = dTable.CreateDataReader()
    While dReader.Read()
        text = dReader.GetValue(0)
    End While
    dReader.Close()

Upvotes: 0

Related Questions