通过Microsoft SQL在VB中连接和筛选组合框

时间:2018-10-24 14:51:26

标签: vb.net winforms

我对编程很陌生,需要一些指导。

我有一个MS SQL数据库项(product_cat,product_type,product_make,product_Model)。我有一个赢奖表格,其中包含与这些列相关的4个组合框。我想要的是能够选择product_cat并根据它过滤product_type。例如:如果我选择类别“运输”,它将与运输相关的所有内容过滤到combobox2(product_type)汽车,公共汽车,火车...中,然后当我选择汽车时,它将过滤并填充combobox3(product_make)。现在,我的代码显示了所有组合框中的所有内容,并且不会过滤任何内容。感谢您的指导。

Public Class Form1 
   Public sql As New sqlcontrol 
   Private DBcmd As SqlCommand 
   Public Sub loadcbxCategory()
      cbxCategory.Items.Clear()
      sql.ExeQuery("Select DISTINCT Product_Category From dbo.Product_Data$;") 
      If sql.HasExecption(True) Then Exit Sub 
      For Each r As DataRow In sql.DBDT.Rows
         cbxCategory.Items.Add(r("Product_Category").ToString)
      Next
   End Sub

   Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 
      loadcbxCategory() 
   ...

   Private Sub cbxCategory_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbxCategory.SelectedIndexChanged 
      Dim mysqlconn = New SqlConnection mysqlconn.ConnectionString = ("Server=mojiz-surface\sqlexpress;database=ASI_Inventory;trusted_connection=true;") 

2 个答案:

答案 0 :(得分:0)

尝试执行此操作您只需要输入组合框名称并传递查询参数

Class SurroundingClass
Private path = "Your connection string"
Private con As OleDbConnection = New OleDbConnection(path)

Public Sub ComboData(ByVal cmb As ComboBox, ByVal colname As String, ByVal dbname As String, ByVal wherecondition As String)
    con.open()
    cmb.Items.Clear()
    da = New OleDbDataAdapter("select " & colname & " from " & dbname & " where " & wherecondition, con)
    dt = New DataTable()
    da.Fill(dt)

    For Each row As DataRow In dt.Rows
        cmb.Items.Add(row(0).ToString())
    Next

    con.close()
End Sub

结束班级

答案 1 :(得分:0)

Dim sample as new sqlcommand ("select*From *your datable in sqldatabase*", connection)
Dim adapter as new sqldataAdapter(sample)
Dim table as new DataTable()

adapter.fill(table)
combobox1.DataSource = Table
Combobox1.Valuemember = "No." (NOTE: *Select the column from your sql data table*)

希望它将对您有帮助。