views:

1016

answers:

1

I have a Winforms application and a combobox has it's datasource set to a DataTable when the form loads. The data displays fine in the combobox.

Then after a user clicks a button I want to create a new DataTable and assign that datatable as the datasource for the combobox.

The problem is that after setting the datasource to be the new datatable the items in the combobox don't change. Here is the code I'm using.

dlCustomer.DataSource = Nothing
        dlCustomer.DataSource = dtCustomers
        dlCustomer.DisplayMember = "Name"
        dlCustomer.Refresh()

Does anyone know how to make the correct data be displayed in the combobox the second time I assign the data source for it?

+2  A: 

It should work, at least it did in a quick test I threw together. Here's the code; it just expects a Form with a ComboBox and 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
STW