DropDown with values from a field in an Access db

R

reidarT

How do I on an Aspx-page make a dropdown with values from an Access db?
I have the connection to the db and i already have a table from the db
working OK in a datagrid
on the aspx-page?
reidarT
 
D

David Berry

On the .ASPX page you'd put:

<asp:DropDownList id="listMyList" runat="server"></asp:DropDownList>

Then in your Code Behind Page (or your <script> tag) you'd have something
like this

Imports System.Data
Imports System.Configuration
Imports system.Data.OleDb
Imports System.IO

Protected WithEvents listMyList As System.Web.UI.WebControls.DropDownList

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
'Put user code to initialize the page here

' Check if page is loaded for the first time
If Not Page.IsPostBack Then
' Load the Various Lists on the Page
LoadLists()
End If
End Sub

' Private Method to load the Drop Down List
Private Sub LoadLists()

' load the drop down list
Dim sqlCon As New
OleDBConnection(ConfigurationSettings.AppSettings("ConString"))
Dim sqlStr As String = "SELECT * FROM TABLENAME"
Dim sqlCmd As New OleDBCommand(sqlStr, sqlCon)
Dim mylistReader As OleDBDataReader
Try
sqlCon.Open()

mylistReader =
sqlCmd.ExecuteReader(CommandBehavior.CloseConnection)

listMyList.Items.Add(New ListItem("Select a Choice", "0"))
' loop and add the items
While mylistReader.Read()
listMyList.Items.Add(New ListItem(mylistReader.GetString(1),
mylistReader.GetInt32(0).ToString()))
End While

listMyList.DataBind()
listMyList.SelectedIndex = 0
mylistReader.Close()

Catch ex As Exception

Finally
sqlCon.Dispose()
End Try
End Sub
 
J

Jon Spivey

It would be easier to just bind the list box to the datsource - there's no
need for code behind for a simple job like this
<asp:DropDownList ID="DropDownList1" runat="server"
DataSourceID="SqlDataSource1" DataTextField="Field"
DataValueField="Field1"></asp:DropDownList>

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$
ConnectionStrings:ConnectionString %>" SelectCommand="SELECT Field, Field1
FROM Table"></asp:SqlDataSource>

Cheers,
Jon
 
D

David Berry

Thanks Jon. I haven't tried that. Also, to use asp:SqlDataSource the site
would need the 2.0 Framework installed so it's important to know which
framework version your web server has.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top