ASP.Net/Data Binding/ListBox
Bind DataTable to asp:ListBox
<source lang="csharp">
<%@ 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) lb2.DataSource = MyDT lb2.DataBind() lb2.Items(3).Selected=True End If
End Sub Sub lb1_Clicked(sender As Object, e As EventArgs)
Dim i As Integer lblMessage.Text = "Preferred office color(s):
" For i = 0 To lb1.Items.Count - 1 If lb1.Items(i).Selected Then lblMessage.Text = lblMessage.Text _ & lb1.Items(i).Text & "
" End If Next
End Sub Sub lb2_Clicked(sender As Object, e As EventArgs)
lblMessage2.Text = "ID of Department you work in: " _ & lb2.SelectedItem.Value & "
"
End Sub </SCRIPT> <HTML> <HEAD> <TITLE>ListBox Control Sample Page</TITLE> </HEAD> <BODY > <form runat="server"> <asp:Label
id="lblMessage" runat="server" Font-Bold="True" Text="Preferred office color:"
/>
<asp:ListBox
id="lb1" runat="server" AutoPostBack="True" OnSelectedIndexChanged="lb1_Clicked" Rows=4 SelectionMode="Multiple"
>
<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:ListBox>
<asp:Label
id="lblMessage2" runat="server" Font-Bold="True" Text="ID of Department you work in:
"
/>
<asp:ListBox
id="lb2" runat="server" AutoPostBack="True" Rows=3 OnSelectedIndexChanged="lb2_Clicked" DataTextField="DepartmentName" DataValueField="DepartmentID" BackColor="LightYellow" ForeColor="DarkRed"
> </asp:ListBox> </Form> </BODY> </HTML>
</source>