views:

621

answers:

3

I want to add a "Select One" option to a drop down list bound to a List<T>.

Once I query for the List<T>, how do I add my initial Item, not part of the data source, as the FIRST element in that List<T> ? I have:

// populate ti from data               
List<MyTypeItem> ti = MyTypeItem.GetTypeItems();    
//create initial entry    
MyTypeItem initialItem = new MyTypeItem();    
initialItem.TypeItem = "Select One";    
initialItem.TypeItemID = 0;
ti.Add(initialItem)  <!-- want this at the TOP!    
// then     
DropDownList1.DataSource = ti;
+3  A: 

Update: a better idea, set the "AppendDataBoundItems" property to true, then declare the "Choose item" declaratively. The databinding operation will add to the statically declared item.

<asp:DropDownList ID="ddl" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Value="0" Text="Please choose..."></asp:ListItem>
</asp:DropDownList>

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.appenddatabounditems.aspx

-Oisin

x0n
That's pretty cool. The OP didn't specify ASP.NET but that's a nice trick to know.
Matt Hamilton
That's the trick... much easier than creating a custom element.....thanks!
Ash Machine
+17  A: 

Use the Insert method:

ti.Insert(0, initialItem);
Matt Hamilton
A: 

I am sorry I read it wrong, I made my example for adding it at the end.

Braveyard
Easier just to delete your answer, atarikg. Before it gets too many downvotes! :)
Matt Hamilton
I deleted God ! people are so mean :/
Braveyard