Generic List Insert() method in asp.net c#

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.
GenericListInsertMethod.aspx

<%@ 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;
        }

        colors.Insert(2,"Green");
        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;
        }
    }
</script>

<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>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <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
        </h2>
        <hr width="550" align="left" color="Purple" />
        <asp:Label
             ID="Label1"
             runat="server"
             ForeColor="Green"
             Font-Size="Large"
             Font-Names="Courier New"
             >
        </asp:Label>
        <br /><br />
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Test Generic List Insert() Method"
            Height="45"
            Font-Bold="true"
            ForeColor="DodgerBlue"
            />
    </div>
    </form>
</body>
</html>
Related asp.net examples