13

I have a ASP DropDownList with items added to it. All what I want is to make the selection after the page loaded empty so there is no a selected item.

How can I do that?

Scath
  • 3,777
  • 10
  • 29
  • 40
Eyla
  • 5,751
  • 20
  • 71
  • 116

6 Answers6

22

You can add an empty item to the top of your dropdownlist programmatically like this:

myDropDown.Items.Insert(0, new ListItem(string.Empty, string.Empty));
myDropDown.SelectedIndex = 0;
womp
  • 115,835
  • 26
  • 236
  • 269
4

Not sure I understand your question but try this:

DropDownList1.ClearSelection()

or

DropDownList1.SelectedIndex = -1;
Naeem Sarfraz
  • 7,360
  • 5
  • 37
  • 63
1

If the dropdownlist is being populated by DataSource, is important do the DataBind before the insert. Otherwise the item insertion does not happen.

myDropDown.DataBind();
myDropDown.Items.Insert(0, new ListItem(string.Empty, string.Empty));
myDropDown.SelectedIndex = 0;

https://stackoverflow.com/a/2224636/1467453

Community
  • 1
  • 1
Marco Castelo
  • 56
  • 1
  • 2
  • 4
1

You can set the SelectedIndex property to -1 or you can add an empty entry as the first item in the data source and validate the selection on form submission.

Nick Larsen
  • 18,631
  • 6
  • 67
  • 96
  • 1
    "You can set the SelectedIndex property to -1" this one did not work I set SelectedIndex property to -1 in loadpage event but did not work and it was working if set it to 2 or 3 but not -1. – Eyla Feb 08 '10 at 20:38
1

This should work on the client side:

<asp:DropDownList ID="YourID" runat="server" DataSourceID="YourDataSource
DataTextField="Text" DataValueField="Value" AppendDataBoundItems="True">
    <asp:ListItem Text="" Selected="True"></asp:ListItem>
</asp:DropDownList>
Jason Nickola
  • 123
  • 1
  • 10
0

yourDropDownList.Items.Clear()

To repopulate, you can either add items statically as per womps suggestion (substituting params in the insert() method, or you can populate it dynamically from a data source. The backing store for list items is the ListItemCollection.

flesh
  • 23,725
  • 24
  • 80
  • 97
  • This will remove all items, not just clear the selected item. – womp Feb 08 '10 at 20:30
  • i agree, the question is ambiguous though – flesh Feb 08 '10 at 20:30
  • Agree on the ambiguity - I was just helping to clear up what it would do. Not sure why you were downvoted - sorry if my comment cause that :( – womp Feb 08 '10 at 20:33
  • this one will clear the item list and in this case I need another method to load the list again. – Eyla Feb 08 '10 at 20:43