asp.net - How to use DropDownList DataBound event

DropDownList DataBound Event
.net developers can populate a dropdownlist server controls by items using data bind with various data source controls such as ObjectDataSource, LinqDataSource, SqlDataSource, ArrayList, Array etc. dropdownlist DataBound event occurs after the dropdownlist control bind to a data source. this event notifies dropdownlist control that any data binding logic written for it has completed. we can write an event handler for this event in script section using dropdownlist OnDataBound property.

the following c# example code demonstrate us how can we use dropdownlist DataBound event in asp.net.
DropDownListOnDataBoundEvent.aspx

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

<!DOCTYPE html>

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e)
    {
        string[] colors = { "DarkBlue", "Ivory", "LightPink", "LightSalmon", "CadetBlue" };
        DropDownList1.DataSource = colors;
        DropDownList1.DataBind();
    }

    protected void DropDownList1_DataBound(object sender, EventArgs e)
    {
        Label1.Text = "Pick your favorite color: ";
        Label1.ForeColor = System.Drawing.Color.OliveDrab;
        Label1.Font.Name = "Comic Sans MS";
        Label1.Font.Italic = true;
        DropDownList1.Items[2].Selected = true;
    }
</script>

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