【问题标题】:How to change the data source of a ComboBox?如何更改 ComboBox 的数据源?
【发布时间】:2012-05-23 04:24:42
【问题描述】:

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

'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”字符串。

【问题讨论】:

  • 这是winforms还是asp.net?如果是 asp.net,您需要 .DataBind() 到您的数据源。
  • 假设是 WinForms,问题出在哪里还不是很清楚。不过,我会避免吞下任何例外。您如何验证 m_listAccount 的内容?
  • @LarsTech 我设置了一个断点来检查 m_listAccount 的值。我将调试器设置为显示所有异常,并且我的代码中没有抛出异常。请参阅我添加的注释以了解更多详细信息。

标签: vb.net winforms combobox


【解决方案1】:

试试这个,

cbxAccount.DataSource = Nothing
cbxAccount.DataSource = m_listAccount

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

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

如果m_listAccountDataTable

【讨论】:

  • 我添加了 cbxAccount.DataSource=nothing 并且效果很好。谢谢!
【解决方案2】:

看起来您实际上并没有调用 databind 方法,即

cbxAccount.DataBind()

尝试在设置数据源后将其放入。

【讨论】:

  • 我不认为 Winforms ComboBoxDataBind 方法。您可能会想到 ASP ComboBox。
  • DataBind() 仅适用于 Web 表单而非 winform。仅供参考,请参阅我在询问 OP 的问题中的评论。
  • 是的,抱歉,我想的是 ASP ComboBox。混蛋。
猜你喜欢
  • 2021-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-26
  • 1970-01-01
  • 2013-07-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多