Thursday, January 9, 2014

ASP.NET CheckBoxList and ListBox

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>CheckBoxTest</title>
</head>
<body>
    <form id="Form1" runat="server">
    <div>
        <asp:CheckBoxList ID="CheckBoxList1" runat="server" RepeatDirection="Horizontal"
            AutoPostBack="True" OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged">
            <asp:ListItem Text="Diploma" Value="1"></asp:ListItem>
            <asp:ListItem Text="Graduate" Value="2"></asp:ListItem>
            <asp:ListItem Text="Post Graduate" Value="3"></asp:ListItem>
            <asp:ListItem Text="Doctrate" Value="4"></asp:ListItem>
        </asp:CheckBoxList>
        <br />
        <asp:ListBox ID="ListBox1" runat="server" Height="78px" Width="127px"></asp:ListBox>
        <br />
        <br />
        <asp:Label ID="lblMessage" runat="server" Font-Bold="true"></asp:Label>
    </div>
    </form>
</body>
</html>


using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
public partial class DropDownlist_Default : System.Web.UI.Page
{
    protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        // Everytime the selection changes, clear the items in the listbox
        ListBox1.Items.Clear();
        // Loop thru each litemitem in the checkboxlist
        foreach (ListItem li in CheckBoxList1.Items)
        {
            // If the listitem is selected
            if (li.Selected)
            {
                // Add the listitem text to the listbox
                ListBox1.Items.Add(li.Text);
                // Add the lisitem as an object. This ensures the listitem is 
                // selected in the listbox. For this to work, listbox, 
                // SelectionMode must be set to Multiple. The SelectionMode
                // Property can be set in the HTML source also.
                // ListBox1.SelectionMode = ListSelectionMode.Multiple
                // ListBox1.Items.Add(li);
            }
        }
        // If nothing is selected from the checkboxlist
        if (CheckBoxList1.SelectedIndex == -1)
        {
            // Set the label ForeColor to Red
            lblMessage.ForeColor = System.Drawing.Color.Red;
        }
        // If atleast one listitem is selected
        else
        {
            // Set the label forecolor to black
            lblMessage.ForeColor = System.Drawing.Color.Black;
        }
        // Display the total number of items selected from the checkboxlist
        lblMessage.Text = ListBox1.Items.Count.ToString() + " item(s) selected";
    } 
}

0 comments:

Post a Comment