从其他组合框的选定项目填充组合框

时间:2015-03-25 11:57:04

标签: vb.net combobox

我正在创建一个用户必须提供州名和城市名称的表单。城市取决于国家。

填充城市的代码:

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"

在组合框中,当所选城市发生变化时,我调用城市加载功能来填充城市组合框。 但我不能填充城市组合框。

2 个答案:

答案 0 :(得分:0)

您需要在State Combobox中的Selected_Index_Changed中使用处理程序。从那里调用你的例程来加载城市,在你需要做的城市的SQL中

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

答案 1 :(得分: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