Change ListBox data source programmatically in asp.net c#

Change ListBox data source programmatically
The following asp.net c# example code demonstrate us how can we set or change ListBox server control's data source progrmmatically at run time in an asp.net application. ListBox is an asp.net list web server control which allow us to select one or more items at a time depend on its selection mode.

We can data bind a ListBox control with a DataSource web server control or with a data source object such as Array, ArrayList, Generic List etc. In this example code we demonstrate the way to switch between ListBox data sources. To do this, first we initializes two Array objects and populated them with items.

Nex, we specify the Array object as ListBox control's data source by ListBox DataSource property. Finally, we call the ListBox DataBind() method to populate ListBox control with items. Each single item from source Array generate a ListItem object in ListBox control when we data bind ListBox with Array data source.
ListBoxDataSource.aspx

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

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        string[] controls = { "ListBox", "ImageMap", "FileUpload", "CheckBox" };
        ListBox1.DataSource = controls;
        ListBox1.DataBind();
    }
    protected void Button2_Click(object sender, System.EventArgs e)
    {
        string[] colors = { "Red", "Crimson", "Blue", "Orange" };
        ListBox1.DataSource = colors;
        ListBox1.DataBind();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to change ListBox data source programmatically</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:Red">asp.net ListBox Example:Change DataSource</h2>
        <asp:Label 
             ID="Label1" 
             runat="server"
             Text="asp.net Controls"
             Font-Bold="true"
             ForeColor="SlateBlue"
             >
        </asp:Label>
        <br />
        <asp:ListBox 
             ID="ListBox1"
             runat="server"
             AutoPostBack="false"
             BackColor="Firebrick"
             ForeColor="FloralWhite"
             >
        </asp:ListBox>
        <br /><br />
        <asp:Button 
             ID="Button1" 
             runat="server"
             Text="DataSource Controls"
             Font-Bold="true"
             ForeColor="SaddleBrown"
             OnClick="Button1_Click"
             />
        <asp:Button 
             ID="Button2" 
             runat="server"
             Text="DataSource Colors"
             Font-Bold="true"
             ForeColor="SaddleBrown"
             OnClick="Button2_Click"
             />
    </div>
    </form>
</body>
</html>
More asp.net examples