Populating a Combobox in ASP from the Database

This code shows how to populate a ComboBox from the database easily. The LoadData function is where the data is selected from the database and then in the Page_Load the DataReader returned from the LoadData function is assigned to the ComboBox's DataSource

Source Code


Imports System.Data
Imports System.Data.OleDb

Public Class WebForm1
Inherits System.Web.UI.Page
Protected WithEvents cboLocations As System.Web.UI.WebControls.DropDownList
#Region " Web Form Designer Generated Code "

'This call is required by the Web Form Designer.
Private Sub InitializeComponent()

End Sub

Private Sub Page_Init(ByVal sender As System.Object, ByVal e As System.EventArgs) _
Handles MyBase.Init

'CODEGEN: This method call is required by the Web Form Designer
'Do not modify it using the code editor.
InitializeComponent()
End Sub

#End Region

Private Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _
Handles MyBase.Load

cboLocations.DataSource = LoadData()
cboLocations.DataTextField = "Customer"
cboLocations.DataBind()
End Sub

'This function is used to populate the combobox
Private Function LoadData() As OleDbDataReader
Dim strSQL As String

strSQL = "SELECT Customer from Customers"

Dim myConnection As OleDbConnection = New _
OleDbConnection(ConfigurationSettings.AppSettings("ConnectionString"))

Dim myCommand As OleDbCommand = New OleDbCommand(strSQL, myConnection)

myConnection.Open()
Dim result As OleDbDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)

Return result
End Function

End Class


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: