我想根据同一行中另一个字段的值从 VB 中的数据表中选择某个字段。
在 SQL 中,可以通过编写以下查询轻松完成:
select error_message from table_errors where error_case="condition"
如果我在 VB 中的数据表中填写了我的 SQL 表,我该怎么做?如何根据item("error_Case") 字段在数据表中选择 item("error_message")?
任何帮助,将不胜感激
您可以使用Linq-To-DataSet
:
Dim matchingRows As IEnumerable(Of DataRow) =
From row In table
Where row.Field(Of String)("error_case") = "condition"
如果您只想要一列(当然也可以一步完成):
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
如果您希望它只是单行使用First
或Single
(如果有多行则抛出异常):
Dim error As String = errorMessages.First()
由于First
如果序列为空会引发异常,您可以使用FirstOrDefault
:
Dim error As String = errorMessages.FirstOrDefault() ' is null/Nothing in case of an empty sequence
合二为一(注意 Linq 和DataTable.Select
需要使用循环):
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()
这是粗略代码的工人版本
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()