A simple question about drop-down list in ASP.NET

  • Thread starter Thread starter Water Cooler v2
  • Start date Start date
W

Water Cooler v2

What am I missing here. I bind a drop-down list in ASP.NET placed on a
web form to a DataReader. The binding is done at run-time and not at
design time. Here's the code I write to bind the list:


Private Sub FillRoles()
ddlRole.Items.Clear()

ddlRole.DataSource =
DataServices.DataProvider.GetReader("select [Role ID], [Role Name] FROM
[Role] ORDER BY [Role Name]")
ddlRole.DataBind()
ddlRole.DataMember = "Role"
ddlRole.DataTextField = "Role Name"
ddlRole.DataValueField = "Role ID"
End Sub


However, instead of the role names, what I get in the list is the
string, "System.Data.Common.DbDataRecord" as many times as there are
records.

When I change the code to this:

Private Sub FillRoles()
ddlRole.Items.Clear()

Dim Reader As SqlClient.SqlDataReader =
DataServices.DataProvider.GetReader("select [Role ID], [Role Name] FROM
[Role] ORDER BY [Role Name]")
ddlRole.DataSource = Reader
ddlRole.DataTextField = Reader("Role Name")
ddlRole.DataValueField = Reader("Role ID")
ddlRole.DataBind()
End Sub

it gives me an exception saying, Invalid attempt to read data when no
data is present.

The table does have six records.

I know I am missing a very minute detail here. What is it?
 
Indeed.. you are missing a minute detail :)
You should use ddlRole.DataBind() after specifying the datatextfield and
datavaluefield so the dropdown can understand which columns it should take.
 

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

Back
Top