ASP.net
ASP / ASP.Net / Vignette
ASP / ASP.Net / Oracle
Books RSS Feed for ASPMatrix.com Book Reviews
 
 
Partner Sites
www.learnasp.com
 
ASPFriends.com

www.411asp.net

www.wwwcoder.com
   
ASP.net > CheckBoxList Validation Tutorial
 

Since there is not a built in validator for the CheckBoxList control, you have to custom make one. The code below is one way you can do so.

When the submit button is pressed, sub Control_Click() is run. The calls sub validate_chkboxlist() which makes sure that at lest one checkbox is checked by iterating through the Items collection of the CheckBoxList Control.

 
 
 
View the code to do it below.
 
'------------------- begin code ----------------------------

<%@ Page Language="VB" %>

<script runat="server">
     Dim i as Int32
     Dim valChkBoxList as Boolean

     sub page_load(S as Object, e as EventArgs)
          if not IsPostBack then
               results.text = ""
          end if
     end sub

sub Control_Click(S as Object, E as EventArgs)
     validate_chkboxlist()
     Dim sb as new stringbuilder

     if valChkBoxlist=true then
          sb.append("<b>Results: </b><font color=""#0099FF"">")
          for i = 0 to (pickName.Items.Count-1)
                 If (pickName.Items(i).Selected) then
                       sb.append(pickName.Items(i).value & " ")
                 End if
          next
          sb.append("</font>")
     else
          sb.append ("<font color=""#FF0000""><b>You must select at least one CheckBox!</b></font>")
     end if

     results.text=sb.tostring()
end sub

sub validate_chkboxlist()
     for i = 0 to (pickName.Items.Count-1)
          If (pickName.Items(i).Selected) then
               valChkBoxList=true
               exit sub
          End if
     next
End sub

</script>

<html>
...

<form runat="server">
<asp:checkBoxList id="pickName" font-family="Arial" font-size="12px" runat="server">
     <asp:listitem value="Brent">Brent</asp:ListItem>
     <asp:listitem value="is">is</asp:ListItem> <asp:listitem value="a">a</asp:ListItem>
     <asp:listitem value="REDNECK">REDNECK</asp:ListItem>
</asp:checkBoxList>
<asp:Button id="btnSubmit" text="Run Code >>" onclick="Control_Click" runat="server" /><br />
<asp:literal id="results" runat="server" /><br />
</form>

...
</html>

'------------------- end code ----------------------------

 
       
      Please report all site problems to: webmaster@aspmatrix.com