Monday, December 16

Populate data to Combobox Control

Combobox control let us select an item to the list of items (msdn.microsft/Combobox). Combobox items are sometimes static items and sometimes requires to be binded to database, there are many ways to do it, and one of those using the code below: 

 1. On the Form and Combobox control and name it anything you like 
 2. On Form_Load event and the code below:


Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    'Specify the datasource
    Dim CONNECTION_STRING As String = "Data Source=LOCALHOST;Initial Catalog=DB_NAME; Integrated Security=True"

    Dim conn As SqlConnection = New SqlConnection(CONNECTION_STRING)
    'Specify the SELECT query
    Dim cmd As SqlCommand = New SqlCommand("SELECT ProductName FROM ProductTable", conn)



    'Open the Database
    conn.Open()

    Dim sdr As SqlDataReader = cmd.ExecuteReader

    'Do the adding through looping
    While sdr.Read()
        If Not sdr("ProductName").ToString = String.Empty Then product.Items.Add(sdr.Item("ProductName").ToString)

    End While

    'Close the Database

    conn.Close()

End Sub



No comments:

Post a Comment