DropDownList Data Binding

J

Joe Delphi

Hi,

I am attempting to bind a dropdown list to a SQLDataReader My code
looks like this:

Dim DBComm As New SqlCommand
Dim DBReader As SqlDataReader
DBComm.Connection = DBConn
DBComm.CommandText = "SELECT TESTER FROM PERSONNEL ORDER BY TESTER"
DBReader = DBComm.ExecuteReader()

'Bind the drop down list to the DBReader'
If DBReader.HasRows() Then
ddlstSubBy.DataSource = DBReader
ddlstSubBy.DataTextField = "TESTER"
ddlstSubBy.DataValueField = "TESTER"
ddlstSubBy.DataBind()
End If

The PERSONNEL database table has a single field named TESTER.

When the program attempts to execute the .DataBind() statement, I get an
exception message that says:

"Index 0 is not non-negative and below total rows count."

What does this mean? I know that the query returned 6 rows so the problem
is not that the SQLDataReader is empty.

Any help appreciated.


JD
 
J

Joe Delphi

Yes, in fact I moved the SQLConnection opening to inside of this same
routine, as shown below, but I still get the exact same error message:

Private Sub PopulateSubByBox()
Dim DBConn As New SqlConnection
Dim DBComm As New SqlCommand
Dim DBReader As SqlDataReader
DBConn.ConnectionString = ConnStr
DBComm.Connection = DBConn
DBComm.CommandText = "SELECT TESTER FROM PERSONNEL ORDER BY TESTER"
DBConn.Open()
DBReader = DBComm.ExecuteReader(CommandBehavior.CloseConnection)

'Bind the drop down list to the DBReader'
If (DBReader.HasRows) Then
ddlstSubBy.DataSource = DBReader
ddlstSubBy.DataTextField = "TESTER"
ddlstSubBy.DataValueField = "TESTER"
ddlstSubBy.DataBind()
End If

DBReader.Close()
DBConn.Close()
End Sub
 
T

Teemu Keiski

Try changing the code to looping the DBReader.

While DBReader.Read()
Dim litem As New ListItem(DBReader("TESTER"))
ddlstSubBy.Items.Add(litem)
End While
DBReader.Close()

Normally the error indeed tries to say that there's not that data available,
so test it by chabnging the code to this. Does it now show the records?
 

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

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top