我有一个Winforms应用程序,当表单加载时,组合框将数据源设置为DataTable。组合框中的数据显示正常。
然后在用户单击按钮后,我想创建一个新的DataTable并将该数据表指定为组合框的数据源。
问题是在将数据源设置为新数据表后,组合框中的项目不会更改。这是我正在使用的代码。
dlCustomer.DataSource = Nothing
dlCustomer.DataSource = dtCustomers
dlCustomer.DisplayMember = "Name"
dlCustomer.Refresh()
有没有人知道如何在第二次为其分配数据源时在组合框中显示正确的数据?
答案 0 :(得分:5)
它应该可以工作,至少它是在一个快速测试中我一起扔的。这是代码;它只需要一个带有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