通过选中两列来搜索数据表

时间:2013-05-16 15:17:21

标签: vb.net datatable

我正在开发一个在此链接中识别的搜索过程....

Simplest/fastest way to check if value exists in DataTable in VB.net?

我想使用这种搜索技术,但想知道是否有任何方法可以在流程中添加两列....

Shared Function CheckValue(myTable As DataTable, columnName As String, searchValue As String) As Boolean
For row As DataRow In myTable.Rows
    If row(columnName) = searchValue Then Return True
    Next
    Return False
End Function

我不能使用PK,但想在两个字段中匹配一个字符串,另一个是整数。

感谢,

2 个答案:

答案 0 :(得分:1)

如果要使用该方法在2列中搜索2个值,则:

Shared Function CheckValue(myTable As DataTable, columnName1 As String, searchValue1 As String, columnName2 As String, searchValue2 As Integer) As Boolean
  For row As DataRow In myTable.Rows
    If row(columnName1) = searchValue1 And row(columnName2) = searchValue2 Then Return True
  Next
  Return False
End Function

请注意,上述内容不会检查DBNull值。如果遇到一个,则抛出异常。为了满足DBNull,需要修改if语句。

答案 1 :(得分:0)

或者您可以从选择

中获取一系列行
Dim oRowsInTarget As DataRow() = MyTable.Select("[Col1Name] = '" & SearchVal1 & "' AND [Col2Name] = '" & SearchVal2 & "'")
IF oRowsInTarget.count > 0 Then
    'Do something
End

OR在一个oneliner

If MyTable.Select("[Col1Name] = '" & SearchVal1 & "' AND [Col2Name] = '" & SearchVal2 & "'").Count > 0 Then Return True