Bind DataTable to asp:DropDownList (VB.net) : DropDownList « Data Binding « ASP.Net






Bind DataTable to asp:DropDownList (VB.net)

<%@ Page Language=VB Debug=true %>
<%@ Import Namespace="System.Data" %>
<script runat=server>
Sub Page_Load(ByVal Sender as Object, ByVal E as EventArgs)
    If Not IsPostBack Then
        Dim MyDT As New DataTable
        Dim MyRow As DataRow
        MyDT.Columns.Add(New DataColumn("DepartmentID", _
            GetType(Int32)))
        MyDT.Columns.Add(New DataColumn("DepartmentName", _
            GetType(String)))
        MyRow = MyDT.NewRow()
        MyRow(0) = 1
        MyRow(1) = "Marketing"
        MyDT.Rows.Add(MyRow)
        MyRow = MyDT.NewRow()
        MyRow(0) = 2
        MyRow(1) = "Sales"
        MyDT.Rows.Add(MyRow)
        MyRow = MyDT.NewRow()
        MyRow(0) = 3
        MyRow(1) = "Support"
        MyDT.Rows.Add(MyRow)
        MyRow = MyDT.NewRow()
        MyRow(0) = 4
        MyRow(1) = "Customer Service"
        MyDT.Rows.Add(MyRow)
        ddl2.DataSource = MyDT
        ddl2.DataBind()
        ddl2.Items(3).Selected=True
    End If
End Sub
Sub ddl1_Clicked(sender As Object, e As EventArgs)
    lblMessage.Text = "Preferred office color: " _
        & ddl1.SelectedItem.Text & "<BR>"
End Sub
Sub ddl2_Clicked(sender As Object, e As EventArgs)
    lblMessage2.Text = "ID of Department you work in: " _
        & ddl2.SelectedItem.Value & "<BR>"
End Sub
</SCRIPT>
<HTML>
<HEAD>
<TITLE>DropDownList Control Sample Page</TITLE>
</HEAD>
<BODY >
<form runat="server">
<Font Face="Tahoma">
<asp:Label
    id="lblMessage"
    runat="server"
    Font-Bold="True"
    Text="Preferred office color:"
/>
<BR>
<asp:DropDownList
    id="ddl1" 
    runat="server"
    AutoPostBack="True"
    OnSelectedIndexChanged="ddl1_Clicked"
>
    <asp:ListItem>Blue</asp:ListItem>
    <asp:ListItem>Red</asp:ListItem>
    <asp:ListItem>Green</asp:ListItem>
    <asp:ListItem Selected>Purple</asp:ListItem>
    <asp:ListItem>Black</asp:ListItem>
    <asp:ListItem>Gold</asp:ListItem>
</asp:DropDownList>
<HR>
<asp:Label
    id="lblMessage2"
    runat="server"
    Font-Bold="True"
    Text="ID of Department you work in:<BR>"
/>
<BR>
<asp:DropDownList 
    id="ddl2" 
    runat="server"
    AutoPostBack="True"
    OnSelectedIndexChanged="ddl2_Clicked"
    DataTextField="DepartmentName"
    DataValueField="DepartmentID"
    BackColor="LightYellow"
    ForeColor="DarkRed"
>
</asp:DropDownList>

</Font>
</Form>
</BODY>
</HTML>
           
       








Related examples in the same category

1.Bind Color name to asp:dropdownlist (VB.net)
2.Bind ArrayList to asp:dropdownlist (VB.net)
3.Bind Hashtable to DropDownList (VB.net)
4.ArrayList Data binding for asp:DropDownList (VB.net)
5.Bind arraylist elements to asp dropdown and get selected one (VB.net)
6.Use ArrayList to fill dropdown value (C#)