Question How do I Populate a Combobox from a SQL Datatable

vodkasoda

Member
Joined
Jun 16, 2011
Messages
15
Programming Experience
10+
Pretty basic question I hope ... I am trying to create a basic Windows Form that will allow the user to choose a league from a ComboBox & then send E:Mails depending on what he chooses in another ComboBox.

It is not for use over a network, just on one person's PC so I don't have to worry about massive security issues.

I have designed the Form and I have a very basic SQL database as part of the Project ...

Screenshot - 06_01_2014 , 13_28_41.png

The question is, how do I populate the first ComboBox with the data that is in the Leagues DataSet ? Can I do this, is this data freely available or do I still have to go down the path of creating a ConnectionString and all the DataTable, DataSEt, DataAdapter variables etc. ?

VS2010 automatically gives me the following code ...

VB.NET:
Private Sub KAmail_Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load    
    'TODO: This line of code loads data into the 'DB_KAmailDataSet.Leagues' table. You can move, or remove it, as needed.
    Me.LeaguesTableAdapter.Fill(Me.DB_KAmailDataSet.Leagues)
End Sub

... can I do something similar to "Fill" the ComboBox with the League Names ? The following code adds 1 line per League to the ComboBox, but it's not the Value of the entry, it is a text line that says "KAmail.DB_KAmailDataSet+LeaguesRow" ...

VB.NET:
For MyIx = 0 To DB_KAmailDataSet.Leagues.Count - 1
    KAmail_ComboBox1.Items.Add(Me.DB_KAmailDataSet.Leagues.Item(MyIx))
Next
 
You can get rid of that code for populating the ComboBox. You already have the ComboBox and the DataSet in the designer so you should bind them in the designer.

I see that you have a BindingSource added to the form already. Is that BindingSource bound to the table you want to display in the ComboBox? If so then you can bind the ComboBox to that. If not, add a new BindingSource and bind it to the appropriate table by setting its DataSource property.

Once you have an appropriate BindingSource, select it in the ComboBox's DataSource property. You should then set the DisplayMember of the ComboBox to the name of the column that you want displayed. You can also set the ValueMember to the name of another column that you want access to, usually the primary key. That way, when the user makes a selection, you can get the PK of the selected record from the SelectedValue of the ComboBox.
 

Latest posts

Back
Top