来自DataTable的SELECT值

时间:2013-03-01 09:47:03

标签: vb.net linq datatable

datatable显示DataGridView

我希望用户在datagridview中选择一个值,并使用该值作为过滤器来查找datatable中的其他值。

如下所示:

SELECT col2 from DataTable2 where col1= 
(value in selected cell of the DataGridView)

修改

好的,我添加了一些额外的信息,因为我不确定我是在问正确的问题:

我在datagridview上有一个工具提示,如下所示:

Sub dataGridView1_CellFormatting(ByVal sender As Object, _
    ByVal e As DataGridViewCellFormattingEventArgs) _
    Handles DataGridView1.CellFormatting

    If e.ColumnIndex = Me.DataGridView1.Columns("Last Stop").Index _
        AndAlso (e.Value IsNot Nothing) Then

        With Me.DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex)

            .ToolTipText = '(THIS IS WHERE I'M STUCK)

        End With

    End If

End Sub

我在上面的位置是我想要使用Last Stop中的值所以e.Value在我的DataTable中查找名称 -

  

ToolTipSN.Tables( “DT_ToolTip”)

1 个答案:

答案 0 :(得分:0)

如果您需要严格比较,区分大小写且确切的字词:

Dim selectedCells = DataGridView1.SelectedCells.Cast(Of DataGridViewCell)()
If selectedCells.Any Then
    Dim filteredRows = From row In datatable2
       Join cell In selectedCells On row.Field(Of String)("col2") Equals cell.Value
       Select row
    ' either use For Each to enumerate the result:
    For Each row In filteredRows
        Dim col2 = row.Field(Of String)("col2")
        ' ...
    Next
    ' or use filteredRows.CopyToDataTable to create  a new DataTable from the result
End If

如果您想允许任何选定的单元格并且不区分大小写(没有连接则效率较低):

Dim filteredRows = From row In datatable2
    Where selectedCells.Any(Function(c) StringComparer.OrdinalIgnoreCase.Equals(c.Value, row("col2")))

如果您想允许任何选定的单元格,不区分大小写且部分单词需要匹配:

Dim filteredRows = From row In datatable2
    Where selectedCells.Any(Function(c) CStr(c.Value).
        IndexOf(row.Field(Of String)("col2"), StringComparison.OrdinalIgnoreCase) > -1)