Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add item to the beginning of List<T>?

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; 
like image 392
Ash Machine Avatar asked Dec 24 '08 00:12

Ash Machine


People also ask

How do you add an object to a list?

You insert elements (objects) into a Java List using its add() method. Here is an example of adding elements to a Java List using the add() method: List<String> listA = new ArrayList<>(); listA. add("element 1"); listA.

What method is used to add items to a list object?

The Insert method of List<T> class inserts an object at a given position. The first parameter of the method is the 0th based index in the List. <T>. The InsertRange() method can insert a collection at the given position.

Why does adding a new value to list <> overwrite previous values in the list <>?

Essentially, you're setting a Tag's name to the first value in tagList and adding it to the collection, then you're changing that same Tag's name to the second value in tagList and adding it again to the collection. Your collection of Tags contains several references to the same Tag object!


2 Answers

Use the Insert method:

ti.Insert(0, initialItem); 
like image 58
Matt Hamilton Avatar answered Oct 09 '22 17:10

Matt Hamilton


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

like image 37
x0n Avatar answered Oct 09 '22 15:10

x0n