The following code explains you how to create a DropDownList control through data binding.
Code for the Default.aspx:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<body>
<form id="Form1" runat="server">
<h3>
DropDownList Data Binding Example
</h3>
Select a background color for days in the calendar.
<br>
<br>
<asp:Calendar ID="Calendar1" ShowGridLines="True" ShowTitle="True" runat="server" />
<br>
<br>
<table cellpadding="5">
<tr>
<td>
Background color:
</td>
</tr>
<tr>
<td>
<asp:DropDownList ID="DropDownColors" AutoPostBack="True" OnSelectedIndexChanged="Selection_Change"
runat="server" />
</td>
</tr>
</table>
</form>
</body>
</html>
Code for Default.aspx.vb
Imports System.Data
Partial Class _Default
Inherits System.Web.UI.Page
Sub Selection_Change(ByVal sender As Object, ByVal e As EventArgs)
' Here we set the background color for days in the Calendar control
' based on the value selected in the DropDownList control.
Calendar1.DayStyle.BackColor = _
System.Drawing.Color.FromName(DropDownColors.SelectedItem.Value)
End Sub
Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
' Load data for the DropDownList control only once, when the
' page is first loaded.
If Not IsPostBack Then
' These few lines for Specify the data source and field names for the Text
' and Value properties of the items in the DropDownList control.
DropDownColors.DataSource = CreateDataSource()
DropDownColors.DataTextField = "ColorListTextField"
DropDownColors.DataValueField = "ColorListValueField"
' Bind the data to the control.
DropDownColors.DataBind()
' Set the default selected item, if desired.
DropDownColors.SelectedIndex = 0
End If
End Sub
Function CreateDataSource() As ICollection
' Create a table to store data for the DropDownList control.
Dim dt As DataTable = New DataTable()
' Define the columns of the table.
dt.Columns.Add(New DataColumn("ColorListTextField", GetType(String)))
dt.Columns.Add(New DataColumn("ColorListValueField", GetType(String)))
' Populate the table with sample values.
dt.Rows.Add(CreateRow("Black", "Black", dt))
dt.Rows.Add(CreateRow("Silver", "Silver", dt))
dt.Rows.Add(CreateRow("White", "White", dt))
dt.Rows.Add(CreateRow("Blue", "Blue", dt))
dt.Rows.Add(CreateRow("Yellow", "Yellow", dt))
' Create a DataView from the DataTable to act as the data source
' for the DropDownList control.
Dim dv As DataView = New DataView(dt)
Return dv
End Function
Function CreateRow(ByVal Text As String, ByVal Value As String, ByVal dt As DataTable) As DataRow
' Create a DataRow using the DataTable defined in the
' CreateDataSource method.
Dim dr As DataRow = dt.NewRow()
dr(0) = Text
dr(1) = Value
Return dr
End Function
End Class
Happy Coding!