Populate a Dropdown List box using VB.NET and Code-behind page



Populate a Dropdown using VB.NET and Code-behind

This simple example demonstrates how to populate a dropdown box using a code-behind page.  This is one method of separating presentation from business logic.

 

ASPX page

<%@ Page Language=”VB” debug=”true” Inherits=”myCodeBehind” src=”2.vb”%>
<html>
<title>Fill dropdown with VB, Sql DataReader & Code Behind</title>
</head>
    <body>
    <asp:Dropdownlist id=”atMyDropDownList” DataValueField = “au_lname” DataTextField = “au_id” runat=”server” />
    </body>
</html>

Code behind form

Imports System
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

public class myCodeBehind : Inherits System.Web.UI.Page

    public atMyDropDownList as DropDownList

    private Sub Page_Load(Sender as object, e as System.EventArgs)
        dim sqlText as string = “select * from authors”
        atMyDropDownList.DataSource = GetDr( sqlText )
        atMyDropDownList.DataBind()
    End Sub

    private Function GetDr(sqlText as string) as SqlDataReader
        dim dr as SqlDataReader
        dim sqlConn as SqlConnection = new SqlConnection(ConnectionString())
        dim sqlCmd as SqlCommand = new SqlCommand(sqlText,sqlConn)
        sqlCmd.Connection.Open()
        dr = sqlCmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
        return dr
    End Function

    private Function ConnectionString() as string
            dim myConn as string = ConfigurationSettings.AppSettings(“DSN_pubs”)
            return myConn
    End Function

    private Sub Page_Init(Sender as object, e as System.EventArgs)
                   
    End Sub

End Class

Web.Config

<configuration>
    <appSettings>
        <add key=”DSN_NorthWind” value=”server=(local)NetSDK;database=NorthWind;Trusted_Connection=yes” />
        <add key=”DSN_pubs” value=”server=(local)NetSDK;database=pubs;Trusted_Connection=yes” />
    </appSettings>
</configuration>

[gp-comments width="770" linklove="off" ]