DropDownList data source
The following asp.net c# example code demonstrate us how can we programmatically
switch between DropDownList's two or more data sources. We can data bind a DropDownList control programmatically with
many different types data source objects such as Array, ArrayList, Generic List and with many DataSource controls such as
SqlDatSource, AccessDataSource, ObjectDataSource server controls.
To programmatically switch between data source objects, first we need to create data source object and populate it with items. Next, we can define the data source object as DropDownList control's DataSource. At last we can call the DropDownList DataBind() method to populate DropDownList with items from specified data source object.
In this example, we created two String Array data source objects. We populated both Array objects with items. Finally, we specify the requested data source as DropDownList control's DataSource object. Web browser render DropDownList control with different items by clicking the different button.
To programmatically switch between data source objects, first we need to create data source object and populate it with items. Next, we can define the data source object as DropDownList control's DataSource. At last we can call the DropDownList DataBind() method to populate DropDownList with items from specified data source object.
In this example, we created two String Array data source objects. We populated both Array objects with items. Finally, we specify the requested data source as DropDownList control's DataSource object. Web browser render DropDownList control with different items by clicking the different button.
DropDownListDataSource.aspx
<%@ Page Language="C#" %>
<!DOCTYPE html>
<script runat="server">
protected void Button1_Click(object sender, System.EventArgs e)
{
string[] colors = { "Coral", "Crimson", "DarkBlue", "DarkCyan" };
DropDownList1.DataSource = colors;
DropDownList1.DataBind();
Label1.Text = "Color List";
}
protected void Button2_Click(object sender, System.EventArgs e)
{
string[] controls = { "ListView", "DataList", "TableRow", "ListBox" };
DropDownList1.DataSource = controls;
DropDownList1.DataBind();
Label1.Text = "Control List";
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>How to set, change DropDownList data source programmatically</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2 style="color:Red">DropDownList: Change DataSource</h2>
<asp:Label
ID="Label1"
runat="server"
Font-Bold="true"
ForeColor="DodgerBlue"
>
</asp:Label>
<asp:DropDownList
ID="DropDownList1"
runat="server"
>
</asp:DropDownList>
<br /><br />
<asp:Button
ID="Button1"
runat="server"
Font-Bold="true"
ForeColor="SteelBlue"
Text="DataSource Colors"
OnClick="Button1_Click"
/>
<asp:Button
ID="Button2"
runat="server"
Font-Bold="true"
ForeColor="SteelBlue"
Text="DataSource Controls"
OnClick="Button2_Click"
/>
</div>
</form>
</body>
</html>


