Problem
In a drop down list connected to a ListT>, I’d like to add a “Select One” option.
Once I query for the List, how do I add my initial Item, not part of the data source, as the FIRST element in that List ? I’ve got:
// 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;
Asked by Ash Machine
Solution #1
Use the Insert method to get started:
ti.Insert(0, initialItem);
Answered by Matt Hamilton
Solution #2
Setting the “AppendDataBoundItems” property to true, then declaring the “Choose item” declaratively, is a better idea. The databinding action will be applied to the item that has been statically declared.
<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
Answered by x0n
Solution #3
You can utilize the side-effect-free Prepend() and Append() methods since.NET 4.7.1. (). The final result will be an IEnumerable.
// Creating an array of numbers
var ti = new List<int> { 1, 2, 3 };
// Prepend and Append any value of the same type
var results = ti.Prepend(0).Append(4);
// output is 0, 1, 2, 3, 4
Console.WriteLine(string.Join(", ", results ));
Answered by aloisdg
Solution #4
Use the ListT> Insert method:
var names = new List<string> { "John", "Anna", "Monica" };
names.Insert(0, "Micheal"); // Insert to the first element
Answered by Sina Lotfi
Solution #5
Use List.Insert
While it is not relevant to your example, if performance is critical, consider using LinkedListT> instead of ListT> because inserting an item at the beginning of a ListT> requires all items to be shifted over. See When Should I Use a List vs. a LinkedList for further information.
Answered by sonny
Post is based on https://stackoverflow.com/questions/390491/how-to-add-item-to-the-beginning-of-listt