如何更改ComboBox的数据源?

时间:2012-05-15 15:53:33

标签: vb.net winforms combobox

我有两个组合框。 combobox1的数据是一个固定的字符串列表。 Combobox2的数据源将是一个字符串列表,取决于combobox1的选择。这与以下常见情况非常相似:首先输入您的contry,然后根据您的输入,第二个组合框将显示该国家的大学列表。

'Change selection of first combobox
Private Sub cbxClient_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cbxClient.SelectedIndexChanged
  Try
    If cbxClient.SelectedIndex <> -1 Then
      GetAccount()
    End If
  Catch
    Throw
  End Try
End Sub

'Based on selection of first combobox, update the data sorce of second combobox
Private Sub GetAccount()
  Try
    m_listAccount.Clear()

    Dim strClient As String = cbxClient.SelectedItem.ToString

    For i As Integer = 0 To m_listDS.Count - 1
      If m_listDS(i).Client.Tostring = strClient Then
        m_ds = m_listDS(i)
        Exit For
      End If
    Next

    If Not m_ds Is Nothing Then
      For Each row As DataRow In m_ds.Tables("Account").Rows
        m_listAccount.Add(row("account").ToString)
      Next
    End If

    cbxAccount.DataSource = m_listAccount

  Catch ex As Exception
  End Try
End Sub

我的问题是虽然m_listAccount更新(具有正确的信息),但cbxAccount中显示的选项不会根据m_listAccount更新(具有错误的信息)。我不明白为什么会这样。

注意:假设m_listAccount中的旧字符串为{“old1”}(列表只有1个字符串),更新后,m_listAccount中的字符串为{“new”}。通过断点,我得到以下内容:

cbxAccount.DataSorce={"new"}
cbxAccount.SelectedItem={"old1"}

在表单中,cbxAccount显示“old1”字符串。

2 个答案:

答案 0 :(得分:1)

试试这个,

cbxAccount.DataSource = Nothing
cbxAccount.DataSource = m_listAccount

如果您只是更新相同的列表对象,则数据源可能不会自动更新,但如果指针更改为数据源,则应该更新。

或者你可以试试,      m_listAccount.AcceptChanges()

如果m_listAccountDataTable

答案 1 :(得分:0)

看起来你实际上并没有调用数据绑定方法,即

cbxAccount.DataBind()

在设置数据源之后尝试放置它。