asp.net 1 drop down lists

E

eagle

When I load a drop down list from a dataset, it defaults to selecting the
first item. How do I get it to not select anything and leave the ddl blank
until a user selects an item? I tried:

ddl.SelectedIndex = -1
but it still selects the first item, returning the selected index of 0

Thanks for your help.
 
G

Greg Burns

I don't think you can do that. You have to add a "--make a selection-"
option to your list of items.

An easy way to do that is to bind your dropdownlist, then add code like
this:

DropDownList.Datasource = foobar
DropDownList.DataBind
DropDownList1.Items.Insert(0, "-make a selection-")

You can put a requirefield validator on it to make sure they choose
something other than that first selection.

Greg
 
G

Greg Burns

That true. Your first choice doesn't really have to have any text in it. :)

Greg
 
S

Scott M.

If you are going to add a required field validator to ensure that any choice
but the first is chosen, you'd have to add the following, otherwise the
newly added first choice would be considered a valid selection:


DropDownList.Datasource = foobar
DropDownList.DataBind
DropDownList1.Items.Insert(0, "-make a selection-")
--------------------> dropdownlist.SelectedItem.Value = ""
<----------------------------------
 
G

Greg Burns

I usually do it like so:

DropDownList1.Items.Insert(0, New ListItem("-make a selection-",""))

For some reason I was thinking DropDownList1.Items.Insert(0, "-make a
selection-") made the value="". But I guess it just defaults value to
whatever the text is instead.

Greg
 
S

Scott M.

All list item values default to the text of the item, unless otherwise
specified. So, you need to null out the value of the first choice if you
don't want the required field validator to allow that choice.

As for creating a New ListItem during the Insert, it really isn't necessary
since Insert implicitly creates a new ListItem anyway. With your code, in
the end, you'd have 2 new list items created in memory, when you only wanted
one.
 
G

Greg Burns

Are you sure? Insert only implicitly createa a new ListItem if you pass it
a string. I am passing it a ListItem as an argument using one of its
overloaded methods.
 
S

Scott M.

Oh yes, sorry about that... you are right. Since you are passing a listitem
(using an overloaded Insert method), it would not create a second listitem.

I still prefer to pass just the string though (less code = less work).

:)
 

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