1st element not displaying in a List Box

G

gurvar

Hi,
I'm trying to populate a list box with items from a db based
on selection from a combo id.
If there are 2 elements, the 1st is getting left out
If there are 4 elements, teh 1st is getting left out
Thanks in advance,

Following is the code:
Try

'Response.Write(strSQlQuery)

'Get a new datareader from our command

myDatareader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)

'we've got our data ...now connect it to our list:

If myDatareader.Read = True Then

ListBox1.DataSource = myDatareader

ListBox1.DataValueField = "Unselected_Task_ID"

ListBox1.DataTextField = "Unselected_List_VC"

ListBox1.DataBind()

myDatareader.Close()

myConnection.Close()

' Next myDatareader

Else

ListBox1.Items.Insert(0, "---No Data---")

End If


Catch myException As Exception

Response.Write("An error has occured: " & myException.ToString())

'Finally

' If Not myDatareader Is Nothing Then

' End If

End Try
 
T

Teemu Keiski

Hi,

it is because you call DataReader.Read initially before binding to the list.
That would set the cursor one step further and make you miss the first item
(when binding, the combo/listbox calls it also).

You would need to bind the reader without calling Read first and if you need
to know does it have rows, use DataReader.HasRows property before binding
(in .NET v1.1) or check the ListBoxs Combo's Items.Count after databinding
(v1.0). If the count is 0, you know that there was nothing to bind.

Second way is just using DataTables/DataSet when you wouldn't have these
issues.
 

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,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top