c# - How to sort an array elements

Array Sort(Array) Method
.Net framework Array.Sort(Array) method allow us to sort the elements in an entire one-dimensional Array using the IComparable implementation of each element of the Array. the array Sort() method exists in System namespace.

array Sort(Array) method require to pass a parameter named 'array'. this 'array' parameter value type is System.Array which represents the one-dimensional array to sort.

array Sort() method throw ArgumentNullException, if the 'array' is null. this method throw RankException, if 'array' is multidimensional. the Sort() method also throw InvalidOperationException exception, if one or more elements in 'array' do not implement the IComparable interface.

the following asp.net c# example code demonstrate us how can we sort array elements alphabetical order programmatically at run time in an asp.net application.
ArraySort.aspx

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

<!DOCTYPE html>

<script runat="server">
    private string[] favoriteColorArray = { "PapayaWhip", "Crimson", "PaleGreen", "DodgerBlue", "SandyBrown" };

    protected void Page_Load(object sender, System.EventArgs e) {
        ListBox1.DataSource = favoriteColorArray;
        ListBox1.DataBind();
    }

    protected void Button1_Click(object sender, System.EventArgs e)
    {
        Array.Sort(favoriteColorArray);
        ListBox1.DataSource = favoriteColorArray;
        ListBox1.DataBind();
        Label1.Text = "Array Sorted and repopulate ListBox";
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to sort an array in asp.net</title>
</head> 
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Green">asp.net array example: Array Sort</h2>
        <asp:Label 
             ID="Label1" 
             runat="server" 
             Font-Size="Large"
             ForeColor="Crimson"
             Font-Bold="true"
             Font-Italic="true"
             >
        </asp:Label>
        <br /><br />
        <asp:Label 
             ID="Label2" 
             runat="server" 
             ForeColor="HotPink"
             Font-Bold="true"
             Text="The ListBox populated by an array"
             >
        </asp:Label>
        <br />
        <asp:ListBox 
             ID="ListBox1" 
             runat="server" 
             BackColor="OrangeRed" 
             ForeColor="AliceBlue"
             >
        </asp:ListBox>
        <br /><br />
        <asp:Button 
             ID="Button1" 
             runat="server" 
             OnClick="Button1_Click"
             Font-Bold="true"
             Text="Sort Array And RePopulate ListBox"
             ForeColor="DodgerBlue"
             />   
    </div>
    </form>
</body>
</html>
More c# examples