Reputation: 21304
The title pretty much asks the whole question - How can I clear ONLY the databound items from a ASP.NET DropDownList and NOT any items added in Source? If I have the following ddl:
<asp:DropDownList ID="ddl1" runat="server"
Width="300px" AppendDataBoundItems="true">
<asp:ListItem Text="(Please Select)" Value="0" />
</asp:DropDownList>
...and then call the following:
ddl1.Items.Clear()
The all the DDL ListItems go away and next time I rebind, the "(Please Select)" default option is gone.
Is there a more streamlined or elegant way to clear only the databound items but leave the "(Please Select)" default ListItem added in the source? I think I could call the Items.Clear() and pop that default item back in like ddl1.Items.Add(New ListItem("(Please Select)", "0"))
as a new ListItem object, but I wondered if there was a better way to do this?
Thanks!
Upvotes: 3
Views: 6217
Reputation: 1925
How about this easy trick. The best advantage of using this trick is that if you make a custom dropdown list as well, It will work. It has been tested and worked perfectly.
while (ddl1.Items.Count != 1)
{
ddl1.Items.RemoveAt(1);
}
Upvotes: 1
Reputation: 21304
I found no other streamlined or better way than clearing the list and then adding the default item back into the collection like shown below:
ddl1.Items.Clear()
ddl1.Items.Add(New ListItem("(Please Select)", "0"))
Upvotes: 7
Reputation: 67
if the prompt is always the first element, then it will be the 0th item in the items collection. so you could iterate through the items deleting from 1 to N. there is a function to delete by index.
Upvotes: 0