Now In this Article explain How to Get selected Items from the CheckBoxList in comma-separated format and Javascript Validations in CheckBoxList .This is common Requirement while working on asp.net application
aspx code
<%@
Page Language="C#" AutoEventWireup="true" CodeBehind="Checkbox.aspx.cs" Inherits="Asp.net_Sample.Checkbox"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD
XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>CheckBoxes</title>
<script type = "text/javascript">
function validateCheckBoxList(source, args) {
var chkListModules = document.getElementById('<%=
cblCourses.ClientID %>');
var chkListinputs =
chkListModules.getElementsByTagName("input");
for (var i = 0; i
< chkListinputs.length; i++) {
if (chkListinputs[i].checked) {
args.IsValid = true;
return;
}
}
args.IsValid = false;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<fieldset style="width:327px">
<legend>Select Your Skills</legend>
<asp:CheckBoxList ID="cblCourses" runat="server" RepeatColumns="2"
Width="311px">
<asp:ListItem>Asp.net</asp:ListItem>
<asp:ListItem>C#</asp:ListItem>
<asp:ListItem>VB</asp:ListItem>
<asp:ListItem>WCF</asp:ListItem>
<asp:ListItem>Jquery</asp:ListItem>
<asp:ListItem>JavaScript</asp:ListItem>
</asp:CheckBoxList>
<asp:Label ID="lblStatus" runat="server" Text=""></asp:Label>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="Please select at least
one skills."
ClientValidationFunction = "validateCheckBoxList"
Display="static" ForeColor="Red"></asp:CustomValidator><br />
<asp:Button ID="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click"
/>
<asp:Button ID="btnClearSelection"
runat="server"
Text="Clear
Selection"
onclick="btnClearSelection_Click"
Width="82px"
/>
<br />
<asp:Label ID="lblSelectedValues" runat="server"
Text=""
style="color: #FF3300"></asp:Label>
</fieldset>
</div>
</form>
</body>
</html>
using
System.Collections;
protected void Page_Load(object
sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs
e)
{
if (cblCourses.SelectedIndex != 1)
{
lblSelectedValues.Text = "Selectd
Values are =" + GetCheckBoxListSelections();
}
else
{
lblSelectedValues.Text = "Please select
Any course";
}
}
private string
GetCheckBoxListSelections()
{
string[] cblItems;
ArrayList cblSelections = new
ArrayList();
foreach (ListItem
item in cblCourses.Items)
{
if
(item.Selected)
{
cblSelections.Add(item.Text);
}
}
cblItems = (string[])cblSelections.ToArray(typeof(string));
return string.Join(",", cblItems);
}
protected void
btnClearSelection_Click(object sender, EventArgs e)
{
cblCourses.ClearSelection();
lblSelectedValues.Text = string.Empty;
}
}