ASP.Net/Data Binding/CheckBoxList
Bind DataTable to asp:CheckBoxList
<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) cbl2.DataSource = MyDT cbl2.DataBind() End If
End Sub Sub cbl1_Clicked(sender As Object, e As EventArgs)
Dim i As Integer lblMessage.Text = "Preferred office color(s):
" For i = 0 To cbl1.Items.Count - 1 If cbl1.Items(i).Selected Then lblMessage.Text = lblMessage.Text _ & cbl1.Items(i).Text & "
" End If Next
End Sub Sub cbl2_Clicked(sender As Object, e As EventArgs)
Dim i As Integer lblMessage2.Text = "ID of Department(s) you work in:
" For i = 0 To cbl2.Items.Count - 1 If cbl2.Items(i).Selected Then lblMessage2.Text = lblMessage2.Text _ & cbl2.Items(i).Value & "
" End If Next
End Sub </SCRIPT> <HTML> <HEAD> <TITLE>CheckBoxList Control Sample Page</TITLE> </HEAD> <BODY > <form runat="server"> <asp:Label
id="lblMessage" runat="server" Font-Bold="True" Text="Preferred office color(s):"
/> <asp:CheckBoxList
id="cbl1" runat="server" CellPadding="5" CellSpacing="5" RepeatColumns="3" RepeatDirection="Vertical" RepeatLayout="Table" TextAlign="Right" AutoPostBack="True" OnSelectedIndexChanged="cbl1_Clicked"
>
<asp:ListItem>Blue</asp:ListItem> <asp:ListItem>Red</asp:ListItem> <asp:ListItem>Green</asp:ListItem> <asp:ListItem>Purple</asp:ListItem> <asp:ListItem>Black</asp:ListItem> <asp:ListItem>Gold</asp:ListItem>
</asp:CheckBoxList>
<asp:Label
id="lblMessage2" runat="server" Font-Bold="True" Text="ID of Department(s) you work in:
"
/>
<asp:CheckBoxList
id="cbl2" runat="server" AutoPostBack="True" OnSelectedIndexChanged="cbl2_Clicked" DataTextField="DepartmentName" DataValueField="DepartmentID" BackColor = "LightYellow" ForeColor = "DarkRed" BorderColor = "DarkBlue" BorderStyle = 8 TextAlign="Left" RepeatLayout="Table"
> </asp:CheckBoxList> </Form> </BODY> </HTML>
</source>