How to set up the CheckBoxList control in Asp.net - Digital Tool Factory blog How to set up the CheckBoxList control in Asp.net - Digital Tool Factory blog

How to set up the CheckBoxList control in Asp.net

I recently came up with the need to have a validated CheckBoxList in and Asp.net page.  Over the years I’ve come up with a standard way of setting up validated CheckBoxLists, so I thought I would share the method and start the brand new “Code Samples” section..

The aspx code is as follows

<strong>Section Name</strong>
<asp:TextBox ID="tbBox" runat="server" Width="1" BorderColor="White" BackColor="White" BorderStyle="None" />
<asp:CustomValidator ID="cvBox" ValidateEmptyText="true" runat="server" ControlToValidate="tbBox" Display="none" ErrorMessage="<b>Required Field Missing</b><br />You must select at least one option" SetFocusOnError="true" ValidationGroup="Main" onservervalidate="cvBox_ServerValidate" />
<ajaxToolkit:ValidatorCalloutExtender ID="vceBox" runat="server" TargetControlID="cvBox" Width="300" />

<br />

<asp:CheckBoxList ID=”cblForms” runat=”server” RepeatColumns=”2″ RepeatDirection=”Horizontal”>
<asp:ListItem Text=”Option A” Value=”A” />
<asp:ListItem Text=”Option B” Value=”B” />
<asp:ListItem Text=”Option C” Value=”C” />
<asp:ListItem Text=”Option D” Value=”D” />
</asp:CheckBoxList>

Please note, the control that I am validating is actually a 1 pixel wide textbox that one should not type in.

The server validate code is this

protected void cvBox_ServerValidate(object source, ServerValidateEventArgs args)
{
string strCB = CBLValueGet(cblForms);
if (strCB.Length!=0)
{
args.IsValid = true;
}
else
{
args.IsValid = false;
}
}

My ValueGet routine (it loops though everything and makes sure that at least one item was selected is

public static string CBLValueGet(System.Web.UI.WebControls.CheckBoxList list)
{
string strValue = "";
for (int counter = 0; counter < list.Items.Count; counter++)
{
if (list.Items[counter].Selected)
{
strValue += list.Items[counter].Value + ",";
}
}
if (strValue.Length - 1 < 0)
{
strValue = "";
}
else
{
strValue = strValue.Remove(strValue.Length - 1, 1);
}

return strValue;
}

The part of the code that fires after the main submit button is pressed is as follows

string strCB = Utility.CBLValueGet(cblForms);
char[] sep = { ',' };
string[] ProdList = strCB.Split(sep);
foreach (string str in ProdList)
{
if (str.Length != 0)
{
//soemtihg happens here with the str value;
}
}

That’s it!

 

This post originally appeared on the Stronico blog – with the absorption of Stronico into Digital Tool Factory this post has been moved to the Digital Tool Factory blog

Tags:

 

Written By Steve French

 

Leave a Reply

Your email address will not be published. Required fields are marked *






Copyright 2011 Digital Tool Factory. All Rights Reserved. Powered by raw technical talent. And in this case, WordPress.