Poulating a DropDownList with a database query

  • Thread starter Thread starter Rob Venable
  • Start date Start date
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
 
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.
 
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
 
Back
Top