简体   繁体   中英

Query Result as Datasource for ComboBox (VB.Net)

I have two Comboboxes and a DataGridView. the first ComboBox looks at column of the DataGridView for its values. I need the second ComboBox to look at the value of the first and then get the values from the table filtered by the Value of the first ComboBox.

I get the information for the first ComboBox like this: (This runs on the "Form Load" Event)

    With FItemTypeComboBox
        .DataSource = DbStarFliteSystemsDataset.tblItems
        .ValueMember = "fItemType"
    End With

For the second ComboBox's Datasource, I want to run a query that functions something like:

    SELECT DISTINCT fItemName FROM tblItems
    WHERE "fItemType" = FItemTypeComboBox.Text

But I don't know where or how to implement this.

I have tried the following, but no matter what variation I run, it always fails:

Private Sub FItemNameComboBox_Enter(sender As Object, e As EventArgs) Handles FItemNameComboBox.Enter

    Dim table As DataTable = New DataTable("tblItems")

    table.Columns.Add("fItemType")
    table.Columns.Add("fItemName")

    Dim Result() As DataRow = table.Select("fItemType" = FItemTypeComboBox.Text)

    With FItemNameComboBox
        .DataSource = Result
        .ValueMember = Result.ToString
    End With

End Sub

I am using Visual Studio 2013 and (obviously) Visual Basic.

You can do it using a DataView . A DataView act like a wrapper for a DataTable, supporting editing, filtering and sorting.

Private Sub FItemTypeComboBox_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles FItemTypeComboBox.SelectedIndexChanged

    Dim selected As Object = Me.FItemTypeComboBox.SelectedItem

    If (TypeOf selected Is DataRowView) Then

        Dim row As DataRow = DirectCast(selected, DataRowView).Row
        Dim fItemType As String = CStr(row.Item("fItemType"))
        Dim view As New DataView(DbStarFliteSystemsDataset.tblItems)

        view.RowFilter = String.Format("[fItemType]='{0}'", fItemType)

        Me.FItemNameComboBox.DataSource = view.ToTable(True, "fItemName")
        Me.FItemNameComboBox.DisplayMember = "fItemName"

    End If

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM