Populate combobox from dataset
Posted on 2004-10-16
I am writing a WinForms application in VB.Net. I have a combobox which I want to populate at runtime from my SQL database. I need some code to do this, BUT...
My database contains the following columns:-
LetterGroupName contains 4 different categories, but each of those categories might contain any number of letters. Therefore, I cannot simply populate the combobox with the result of a dataset fill from this table, otherwise when the user tries to select a category of letters, the combobox might contain repetitions, eg...
etc etc - you know what I mean!!
Please give me some sample code for this. At the moment, I am trying something on the following lines, but I can't seem to get it working:-
daMergeDocs.SelectCommand = New SqlCommand
daMergeDocs.SelectCommand.Connection = MergeDocsSqlConnection
daMergeDocs.SelectCommand.CommandText = "SELECT LetterGroupName " & "FROM dtLetters " & "ORDER BY LetterName"
daMergeDocs.SelectCommand.CommandType = CommandType.Text
cboMergeCategory.ValueMember = "id"
cboMergeCategory.DisplayMember = "LetterGroupName"
cboMergeCategory.DataSource = dt
I think I know the logic for this, but not the coding!! - Something like: For Each different entry in LetterGroupName add one item to the combobox items collection.
I could hard-code the combobox items collection at design time, but ultimately I might give the user the option to create new categories of letters, which would then require a corresponding item in the combobox.
Thanks in advance :D