ASP.NET, Coding

Dynamically Populate Combo Box using Dataset

This function below show how to load your combo boxes with values from a SQL Database dynamically using Dataset. This function takes 2 parameters as ComboBox and Dataset. The variable cnt used to get the count of records is global integer variable.

 Private Sub FillInCombo(ByRef cbo As System.Windows.Forms.ComboBox, ByRef ds As DataSet)

        Dim I As Short
        Dim iRec As Short
        cnt = ds.Tables(0).Rows.Count
        If cnt > 0 Then
            iRec = cnt
            'This inserts a value in the collection to a specific index
            cbo.Items.Insert(0, "")
            For I = 1 To iRec
                If Not IsDBNull(ds.Tables(0).Rows(I - 1).Item(0).ToString()) And Trim(ds.Tables(0).Rows(I - 1).Item(0).ToString()) <> "" Then
                    cbo.Items.Add(Trim(ds.Tables(0).Rows(I - 1).Item(0).ToString()))
                End If
                System.Windows.Forms.Application.DoEvents()
            Next I
            cbo.SelectedIndex = 0
        End If
    End Sub

You Might Also Like