按ListBox项筛选SQL数据以在DataGridViews中显示

时间:2015-10-13 12:10:15

标签: vb.net

我无法正确过滤列表框项目。

基本上,我想点击ListBox中的一个项目,然后相应地填充DataGridView。我有2个DataGridViews,它将根据所选的ListBox项显示不同的条件。

到目前为止,我的代码如下:

Public Class Form1

    Dim str As String = "Data Source=XXXXX;Initial Catalog=XXXXXX;Integrated Security=True"
    Dim con As New SqlConnection(Str)
    Dim com As String = "Select swname, numoflic from SW2"
    Dim com2 As String = "Select name, instdate, swinsta, organ from Assigned2"
    Dim Adpt As New SqlDataAdapter(com, con)
    Dim Adpt2 As New SqlDataAdapter(com2, con)
    Dim ds, ds2 As New DataSet()

Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
    Dim dt As DataTable
    dt = New DataTable("SW2")

    'DEFINING LISTBOX ITEM AS STRING
    Dim curItem As String = ListBox1.SelectedItem.ToString()

    ds.Tables.Clear()
    ds2.Tables.Clear()

    Adpt.Fill(ds, "ContactPerson2")
    DataGridView1.DataSource = ds.Tables(0)

    Adpt2.Fill(ds2, "Assigned2")
    DataGridView2.DataSource = ds2.Tables(0)

End Sub

2 个答案:

答案 0 :(得分:0)

您需要按照here说明过滤数据集。另外,我建议你不要在事件处理程序中重新填充数据表。在Form_Load中加载它们,然后只将Nothing传递给过滤器,以清除SelectedIndexChanged事件处理程序开头的任何先前过滤器。

答案 1 :(得分:0)

我改变了一些代码,现在对我有用的是下面的代码。

    Dim curItem As String = ListBox1.SelectedItem(1)
    Dim sqlConnectionString As String = "Data Source=XXXX;Initial Catalog=XXXXX;Integrated Security=True"
    Dim sqlSelect As String = "Select swname, number from SW"
    Dim da As New SqlDataAdapter(sqlSelect, sqlConnectionString)
    Dim dt As New DataTable

    da.Fill(dt)

    'filter setting defined here
    Dim filter As String = "swname = '" + curItem + "'"

    'filter rows
    Dim FilteredRows As DataRow() = dt.Select(filter)

    For Each row As DataRow In FilteredRows
        DataGridView1.DataSource = FilteredRows.CopyToDataTable()

    Next