Poulating a DropDownList with a database query

R

Rob Venable

Hi everyone,
Can anyone see a problem with this code. I'm kinda new to asp.net and
I'm having a problem populating a drop down list with a database query.
The results of my query populate the list with the words
"System.Data.Common.DbDataRecord"

This is my code:

If Not Page.IsPostBack Then
Dim cn As New
SqlConnection(ConfigurationSettings.AppSettings("CONN_STRING"))
Dim sql As String = "SELECT * FROM teams "
Dim dr As SqlDataReader
Dim cmd As New SqlCommand(sql, cn)
cn.Open()
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
ddlTeam.DataSource = dr
ddlTeam.DataBind()

cn.Close()
End If

Any help would be greatly appreciated.

Thanks
Rob
 
D

Dune

You need to set the DataTextField property for the
DropDownList control.

Switch to the HTML view of your web form and set the
DataTextField property to the name of the column you want
the DropDownList to display.

So, if you want to display a list of say, offices, it
would look something like this:
(assumming i selected the office_name and office_id
columns from my database into my DataReader)

<asp:dropdownlist id="ddlOffices" runat="server"
datatextfield="office_name"
datavaluefield="office_id"></asp:dropdownlist>

I've also set the DataValueField property above. This is
very handy cos it means when a user selects an office from
the drop down, you can easily find the corresponding id
for the selected office and pass it to your insert/update
statements.
 
R

Rob Venable

Perfect,
Not only did you answer my question but you answered my next question as
to how can I get the ID to write it back to the database.

Thank you very much.

Rob
 

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

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top