我有一个Winforms应用程序,并且在加载表单时,组合框的数据源设置为DataTable。数据在组合框中显示正常。
然后,在用户单击按钮之后,我想创建一个新的DataTable并将该数据表分配为组合框的数据源。
问题在于,将数据源设置为新的数据表后,组合框中的项目不会更改。这是我正在使用的代码。
dlCustomer.DataSource = Nothing dlCustomer.DataSource = dtCustomers dlCustomer.DisplayMember = "Name" dlCustomer.Refresh()
有谁知道我第二次为其分配数据源时如何使正确的数据显示在组合框中?
它应该起作用,至少在我一起进行的快速测试中确实如此。这是代码;它只是期望一个带有ComboBox和Button的窗体:
Public Class Form1 Private dtOne As DataTable Private dtTwo As DataTable Private Sub InitializeTables() dtOne = New DataTable("TableOne") With dtOne .Columns.Add("Text", GetType(String)) .Columns.Add("Value", GetType(Integer)) End With dtTwo = New DataTable("TableTwo") With dtTwo .Columns.Add("Text", GetType(String)) .Columns.Add("Value", GetType(Integer)) End With Dim newRow As DataRow For index As Integer = 0 To 2 newRow = dtOne.NewRow newRow.ItemArray = (New Object() {SpellIt(index), index}) dtOne.Rows.Add(newRow) Next For index As Integer = 2 To 0 Step -1 newRow = dtTwo.NewRow newRow.ItemArray = (New Object() {SpellIt(index), index}) dtTwo.Rows.Add(newRow) Next dtOne.AcceptChanges() dtTwo.AcceptChanges() End Sub Private Shared Function SpellIt(ByVal int As Integer) As String Select Case int Case 0 : Return "Zero" Case 1 : Return "One" Case 2 : Return "Two" Case Else : Throw New ArgumentOutOfRangeException("Bleh!") End Select End Function Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load InitializeTables() Me.Label1.DataBindings.Add("Text", ComboBox1, "SelectedValue") Me.ComboBox1.DataSource = dtOne Me.ComboBox1.DisplayMember = "Text" Me.ComboBox1.ValueMember = "Value" End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Me.ComboBox1.DataBindings.Clear() Me.ComboBox1.DataSource = Nothing Me.ComboBox1.DataSource = dtTwo Me.ComboBox1.DisplayMember = "Text" Me.ComboBox1.ValueMember = "Value" End Sub End Class