fill combobox with data taken from database

swethajain

Well-known member
Joined
Feb 1, 2010
Messages
48
Programming Experience
Beginner
Hi,
I have a combobox & i want to fill the combox with data from the database when thr form is initialised.Can anyone tell me the code?

Thanks,
Swetha.
 
Since you didn't say what kind of database you are using, I just picked SQL Server at randem. This may work with other kinds of databases
VB.NET:
'assumes myConnection is a valid database connection

 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim sSQL As String
        sSQL = "SELECT field1 "
        sSQL = sSQL & "FROM table1 "
        sSQL = sSQL & "ORDER BY field1"
        Dim command As New SqlCommand(sSQL, myConnection)
        Dim reader As SqlDataReader = command.ExecuteReader()

        While reader.Read()
            ComboBox1.Items.Add(reader.GetString(0)
        End While
    End Sub
 
Hack, you use a more modern version of VS than I do; why do you keep posting VB6 code from the early 90s?

You'll save yourself a lot of finger wear, and be doing people a bigger favour if you start them off down the track of following proper Microsoft tutorials about building a sensible data access layer, instead of teaching them bad habits such as filling button handlers full of SQL. If you wish to remain in the dark ages, please do the newbies the courtesy of not dragging them in there with you.

Swetha, follow the advices you'll find in the DW2 link in my signature. Start with Creating a Simple Data App. When you want to put a combo on a form, expand the Data Soruces window to find the item whose entries you want in the combo, change the item type to combobox and drag it to the form.
 
Combo

Hi,
I have a combobox & i want to fill the combox with data from the database when thr form is initialised.Can anyone tell me the code?

Thanks,
Swetha.


OLEDB
I use this combobox for for selecting records to edit or delete

Private Sub Md_FillCombo()
Try
Dim r As DataRow
comboBoxNo.Items.Clear()
For Each r In dSet.Tables(0).Rows
comboBoxNo.Items.Add(r.Item(0))
Next r
btnUpdate.Enabled = False
btnDelete.Enabled = False
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Sub


Here's the code for its indexing

Private Sub comboBoxNo_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles comboBoxNo.SelectedIndexChanged
Try
dSet.Tables(0).PrimaryKey = New DataColumn() {dSet.Tables(0).Columns("NO_0")}
Dim row As DataRow
row = dSet.Tables(0).Rows.Find(comboBoxNo.Text)
txtBoxNo.Text = row("NO_0")
txtBoxName.Text = row("NAME_0")
txtBoxGender.Text = row("GENDER_0")
txtBoxDepartment.Text = row("DEPARTMENT_0")
txtBoxTotalMark.Text = row("TOTALMARK_0")
btnUpdate.Enabled = True
btnDelete.Enabled = True
txtBoxNo.ReadOnly = True
btnAdd.Enabled = False
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Sub

Hope this helps.:p
 
Back
Top