Fill data into asp:CheckBoxList and get selected items (C#) : CheckBoxList « ASP.net Controls « ASP.NET Tutorial






File: Default.aspx

<%@ Page language="c#" Inherits="CheckBoxTest" CodeFile="Default.aspx.cs" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
 "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <title>CheckBoxTest</title>
</head>
<body>
  <form ID="Form1" runat="server">
    <div>
        Choose your favorite programming languages:<br /><br />
        <asp:CheckBoxList ID="chklst" runat="server" /><br /><br />
        <asp:Button ID="cmdOK" Text="OK" runat="server" OnClick="cmdOK_Click" />
        <br /><br />
        <asp:Label ID="lblResult" runat="server" />
    </div>
  </form>
</body>
</html>


File: Default.aspx.cs

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 CheckBoxTest : System.Web.UI.Page
{
  protected void Page_Load(object sender, System.EventArgs e)
  {
    if (this.IsPostBack == false)
    {
      chklst.Items.Add("C");
      chklst.Items.Add("C++");
      chklst.Items.Add("C#");
      chklst.Items.Add("Visual Basic 6.0");
      chklst.Items.Add("VB.NET");
      chklst.Items.Add("Pascal");
    }
  }
  protected void cmdOK_Click(object sender, System.EventArgs e)
  {
    lblResult.Text = "You chose:<b>";

    foreach (ListItem lstItem in chklst.Items)
    {
      if (lstItem.Selected == true)
      {
        // Add text to label.
        lblResult.Text += "<br />" + lstItem.Text;
      }
    }

    lblResult.Text += "</b>";
  }
}








3.12.CheckBoxList
3.12.1.Fill data into asp:CheckBoxList and get selected items (C#)
3.12.2.Adding ListItems from an Array
3.12.3.Adding ListItems from an Array With a Value
3.12.4.Adding ListItems from an Array Using DataBinding
3.12.5.Adding ListItems Declararatively