Using DropDownLists

E

et

How can I add a blank item to a drop down list so that it is the first item
in the list?

My drop down list is bound to a datareader, and if I add a blank item first
as follows --
ddl.Items.Add(New ListItem(" ", 0)) -- then binding erases the blank item.

Or maybe there is another way to solve my problem. An item in the drop down
list is automatically selected by FindByValue:

ddl.SelectedIndex =
ddl.Items.IndexOf(ddl.Items.FindByValue(Session("ID")))

If the above does not find a match, the SelectedIndex defaults to 0, and
hence the first item is selected. Since the first item contains a valid
value, I end up with a false result. I can't have it select the last item
if the SelectedIndex defaults to 0, because then when the first item should
be selected correctly, it ends up blank, again erroneously.

Hope that makes sense. Thanks for your help.
 
R

Riki

I suggest you add the blank item AFTER the databinding.
You can do this by handling the DataBound event for the list,
and adding the item in that handler.
 
G

Guest

Are you adding this new listitem after you have bound to the datareader? If
not I believe you should.

Example:
Try
myConnection.Open()

myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection)

DropDownList1.DataSource = myDataReader
DropDownList1.DataBind()
Catch myException As Exception
Response.Write("An error has occurred: " & myException.ToString())
Finally
If Not myDataReader Is Nothing Then
myDataReader.Close()
End If

DropDownList1.Items.Insert(0, "Select an Item")
DropDownList1.SelectedIndex = 0
End Try
 
E

et

Thanks for your input.

I am adding the blank item after it is bound to the datareader. However, my
problem is not adding it, it adds it in just fine, but it adds it to the
bottom of the list, not the top of the list. I want it to be at the top of
the list.
 
E

Eliyahu Goldin

Use Insert instead of Add.

Eliyahu

et said:
Thanks for your input.

I am adding the blank item after it is bound to the datareader. However,
my problem is not adding it, it adds it in just fine, but it adds it to
the bottom of the list, not the top of the list. I want it to be at the
top of the list.
 

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

Top