ListBox DataBound event in asp.net c#

ListBox DataBound event
The following asp.net c# example code demonstrate us how can we perform some action/task on ListBox control's DataBound event. ListBox is an asp.net list web server control which render a single or multiple selection enabled items collection.

We can populate a ListBox items by data binding it with various data source objects such as Array, ArrayList, Dictionary, Stack, SqlDataSource, ObjectDataSource etc. Each element of data source object generate a new ListItem object in ListBox control while we data bind.

ListBox control's DataBound event occurs after the ListBox control binds to a data source. This DataBound event inform/notify the ListBox control that data binding logic written for this control has completed. We can write an event handler for this DataBound event and can perform any action to ListBox items after data bind complete (on DataBound event).

In this tutorial, we change a Label control's design and style on ListBox control's DataBound event. We also set ListBox control's two items are selected on ListBox DataBound event (after data binding completed).
ListBoxOnDataBoundEvent.aspx

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

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        string[] colors = { "DarkRed", "BlueViolet", "FloralWhite", "Gainsboro", "GhostWhite" };
        ListBox1.DataSource = colors;
        ListBox1.DataBind();
    }

    protected void ListBox1_DataBound(object sender, EventArgs e)
    {
        Label1.Text = "Favorite color: ";
        Label1.ForeColor = System.Drawing.Color.OrangeRed;
        Label1.Font.Name = "Comic Sans MS";
        Label1.Font.Italic = true;
        ListBox1.Items[0].Selected = true;
        ListBox1.Items[2].Selected = true;
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>How to use ListBox OnDataBound event in asp.net</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2 style="color:DarkOrchid; font-style:italic;">
            How to use ListBox
            <br /> OnDataBound event in asp.net
        </h2>
        <hr width="350" align="left" color="Orchid" />
        <asp:Label 
            ID="Label1" 
            runat="server"
            >
        </asp:Label>
        <br />
        <asp:ListBox 
            ID="ListBox1"
            runat="server"
            OnDataBound="ListBox1_DataBound"
            SelectionMode="Multiple"
            Font-Size="Large"
            >
        </asp:ListBox>
        <br /><br />
        <asp:Button 
            ID="Button1"
            runat="server"
            OnClick="Button1_Click"
            Text="Populate ListBox"
            Height="45"
            Font-Bold="true"
            ForeColor="DodgerBlue"
            />
    </div>
    </form>
</body>
</html>
More asp.net examples