ASP.Net/Data Binding/ListBox

Материал из .Net Framework эксперт
Версия от 11:52, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Bind DataTable to asp:ListBox

<%@ 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):<BR>"
    For i = 0 To lb1.Items.Count - 1
        If lb1.Items(i).Selected Then
            lblMessage.Text = lblMessage.Text _
                & lb1.Items(i).Text & "<BR>"
        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 & "<BR>"
End Sub
</SCRIPT>
<HTML>
<HEAD>
<TITLE>ListBox 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: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>
<HR>
<asp:Label
    id="lblMessage2"
    runat="server"
    Font-Bold="True"
    Text="ID of Department you work in:<BR>"
/>
<BR>
<asp:ListBox 
    id="lb2" 
    runat="server"
    AutoPostBack="True"
    Rows=3
    OnSelectedIndexChanged="lb2_Clicked"
    DataTextField="DepartmentName"
    DataValueField="DepartmentID"
    BackColor="LightYellow"
    ForeColor="DarkRed"
>
</asp:ListBox>
</Font>
</Form>
</BODY>
</HTML>