2015-03-25 213 views
0

我正在創建一個窗體,其中用戶必須提供州名和城市名稱。城市依賴於國家。從其他組合框的選定項目填充組合框

代碼用於填充城市:

Dim ds As DataSet = New DataSet 
Dim adapter As New OleDb.OleDbDataAdapter 
Dim sql As String 
    sql = "SELECT * from statestab order by `state` ASC;" 
    adapter.SelectCommand = New OleDb.OleDbCommand(sql, con) 
    adapter.Fill(ds) 
    ComboBoxstate.DataSource = ds.Tables(0) 
    ComboBoxstate.ValueMember = "stateid" 
    ComboBoxstate.DisplayMember = "state" 

代碼爲城市:

Dim ds As DataSet = New DataSet 
Dim adapter As New OleDb.OleDbDataAdapter 
Dim sql As String 
Dim st As Integer 
    st = ComboBoxstate.SelectedValue.ToString() 
    sql = "SELECT * from citytab where stateid=st order by `cityname` ASC;" 
    adapter.SelectCommand = New OleDb.OleDbCommand(sql, con) 
    adapter.Fill(ds) 
    citycombo.DataSource = ds.Tables(0) 
    citycombo.ValueMember = "cityid" 
    citycombo.DisplayMember = "cityname" 

在下拉列表中,當選擇城市化,我撥打市加載功能來填充城市組合框。 但我無法填充城市組合框。

+0

什麼不工作?你得到一個錯誤或國家不顯示? – phil652 2015-03-25 12:18:20

+0

它看起來像你沒有將狀態ID傳入你的第二個查詢中,而只是文本「st」而不是「st」變量的值。除非你在表中有一個名爲'st'的列,否則我希望你看到一個SQL異常? – 2015-03-25 12:39:41

+0

我有一個列名稱stateid城市選項卡,這也是目前statestab – 2015-03-25 16:53:02

回答

0

您需要在狀態組合框中的Selected_Index_Changed中使用處理程序。從那裏,叫你的日常裝載了城,在SQL的城市,你需要做的

where stateid=" & comboBox1.SelectedValue.ToString() 
+0

嘗試過但不工作, – 2015-03-25 16:53:25

0

以下是全文,請注意,是可以要好得多,但我試圖保持你的語法機智:

Private Sub cboState_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboState.SelectedIndexChanged 
    Load_Cities() 

End Sub 

Private Sub Load_States() 
    Dim ds As DataSet = New DataSet 
    Dim adapter As New OleDb.OleDbDataAdapter 
    Dim sql As String 
    sql = "SELECT * from tblState order by StateName ASC;" 
    adapter.SelectCommand = New OleDb.OleDbCommand(sql, con) 
    adapter.Fill(ds) 
    cboState.DataSource = ds.Tables(0) 
    cboState.ValueMember = "stateid" 
    cboState.DisplayMember = "statename" 
End Sub 

Private Sub Load_Cities() 
    On Error Resume Next 

    Dim ds As DataSet = New DataSet 
    Dim adapter As New OleDb.OleDbDataAdapter 
    Dim sql As String 
    sql = "SELECT * from tblCity where StateID = " & cboState.SelectedValue.ToString() & " order by CityName ASC;" 
    adapter.SelectCommand = New OleDb.OleDbCommand(sql, con) 
    adapter.Fill(ds) 
    cboCity.DataSource = ds.Tables(0) 
    cboCity.ValueMember = "CityID" 
    cboCity.DisplayMember = "CityName" 



End Sub 
+0

謝謝我添加StateID =「&cboState.SelectedValue.ToString()這到我的代碼,它是像魅力 – 2015-03-29 15:36:29