c# - How to insert an item into a list

Generic List Insert() Method
.Net framework generic list Insert() method allow us to insert an element into the List<T> at the specified index. List class Insert() method exists under System.Collections.Generic namespace. this method require to pass two parameters named 'index' and 'item'.

the 'index' parameter value data type is System.Int32 that represents the zero-based index at which 'item' should be inserted. the 'item' parameter value type is 'T' that represents the object to insert. this parameter can be null for reference types and also allow duplicate elements.

this method implements as IList<T>.Insert(Int32, T). the Insert() method throw ArgumentOutOfRangeException if the 'index' is less than zero or 'index' is greater than Count.

the following asp.net c# example code demonstrate us how can we insert an element into a generic list at specified index position programmatically at run time in an asp.net application.

<%@ Page Language="C#" AutoEventWireup="true" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
        List<string> colors = new List<string>() {"DarkSalmon","Yellow","Crimson"};

        Label1.Text = "List Elements....<br />";
        foreach (string color in colors)
            Label1.Text += "<br />" + color;

        Label1.Text += "<br /><br />After inserting 'Green' at index 2";

        Label1.Text += "<br />Now List Elements....<br />";
        foreach (string color in colors)
            Label1.Text += "<br />" + color;

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Generic List Insert() - How to insert an element into the List at the specified index</title>
    <form id="form1" runat="server">
        <h2 style="color:Navy; font-style:italic;">
            System.Collections.Generic.List Insert() Method
            <br /> How to insert an element into the List at the specified index
        <hr width="550" align="left" color="Purple" />
             Font-Names="Courier New"
        <br /><br />
            Text="Test Generic List Insert() Method"
Related asp.net examples