Validating or Validation of a CheckBoxList
On my web form I came across an instance that I needed a user to either check a box from a checkboxlist or leave a comment, this then would be emailed to someone. So I needed to validate that a checkbox had been checked or at least a comment was added.
On my button I added onclick=”Control_Click”
<asp:Button id="btnSend" runat="server" CssClass="submitLarge" onclick="Control_Click" Text="SEND"></asp:Button>
Then in the codebehind I added the code to validate and then if validation is true, I send email.
Sub Control_Click(ByVal S As Object, ByVal E As EventArgs) validate_chkboxlist() Dim sb As New System.Text.StringBuilder If valChkBoxList = True Then CreateEmail() Else lblMessage.Text = "<font color=""#FF0000""><b>You must select at least one CheckBox or add a comment!</b></font>" End If End Sub Sub validate_chkboxlist() For ii = 0 To (cblInterest.Items.Count - 1) If (cblInterest.Items(ii).Selected) Or txtComments.Text <> "" Then valChkBoxList = True Exit Sub End If Next End Sub
As you can see, from Control_Click I call the validate_chkboxlist. In validate_chkboxlist I loop through the checkboxes but also check that the comment.text isn’t blank. If a box is checked or the commentbox has text in it, valChkBoxList is marked as true and the email is sent.
