Reputation: 11
I read these before asking:
VB: How to bind a DataTable to a DataGridView?
http://msdn.microsoft.com/en-us/library/fbk67b6z(v=vs.100).aspx
I have a very simple problem. The vb.net winforms project contains several datatables, a combobox and a datagridview.
I can select the datatable to display thus:
datagridview1.datasource = dt1 'or dt2 or dt3
and this works fine.
What I want to do is select the datatable to display from the combobox selection where I have previously defined a combobox collection of items thus:
combobox1.item.add("dt1")
combobox1.item.add("dt2")
combobox1.item.add("dt3")
I placed this line
datagridview.datasource = combobox1.SelectedItem
in the ComboBox1_SelectedIndexChanged
event.
This just blanks my datagridview. My initial thought was that this fails because I am passing a string to something that expects an object so I have tried datagridview.datasource = CObj(combobox1.SelectedItem)
but with no better result.
What simple thing am I doing wrong?
Upvotes: 0
Views: 193
Reputation: 32248
Add your DataTable objects references directly to the ComboBox.Items
collection.
combobox1.DisplayMember = "TableName"
combobox1.DataSource = {dt1, dt2, dt3}
' Or... (DisplayMember value applies anyway)
'combobox1.Items.AddRange({dt1, dt2, dt3})
In the ComboBox SelectionChangeCommitted event handler, set the DataGridView.DataSource
:
Private Sub combobox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles combobox1.SelectionChangeCommitted
dataGridView1.DataSource = DirectCast(combobox1.SelectedItem, DataTable)
End Sub
If you want to use the SelectedIndexChanged
event instead, check whether SelectedIndex < 0
and just Return
if it is.
Upvotes: 1
Reputation: 937
I usually code in c# but this roundabout method would work:
If combobox1.SelectedItem = "dt1" Then
datagridview1.DataSource = dt1
ElseIf combobox1.SelectedItem = "dt2" Then
datagridview1.DataSource = dt2
ElseIf combobox1.SelectedItem = "dt3" Then
datagridview1.DataSource = dt3
End If
Upvotes: 0
Reputation: 992
Your ComboBox
is just a list of strings, so when you do datagridview.datasource = combobox1.SelectedItem
you're not actually setting the datasource to a datatable.
What I would do this this in your ComboBox1_SelectedIndexChanged
event:
Select Case combobox1.SelectedItem
Case "dt1"
datagridview1.datasource = dt1
Case "dt2"
datagridview1.datasource = dt2
Case "dt3"
datagridview1.datasource = dt3
End Select
Upvotes: 0