How to require checkboxes be checked in vb.net - asp.net

Can someone please help me figure out how to require more than one checkbox to be checked on my aspx page? I have found a few articles that show how to do this with JavaScript, but I use VB and I am not sure how to apply it.
What I would like to do is once the user clicks the submit button it will display an error if enough checkboxes have not been checked. These are not in a checkbox list but rather individual checkboxes.

You can use a CustomValidator for this purpose.
Within your ASPX page, you put it in your controls and the validator.
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:Label AssociatedControlID="CheckBox1" runat="server">Check this box!</asp:Label>
<asp:CheckBox ID="CheckBox2" runat="server" />
<asp:Label AssociatedControlID="CheckBox2" runat="server">And this box!</asp:Label>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="You must check all of the boxes"
OnServerValidate="CustomValidator1_ServerValidate">
</asp:CustomValidator>
After this, you can check they click Submit by checking the ServerValidate event.
Protected Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
args.IsValid = True ' set default
If Not CheckBox1.Checked Then
args.IsValid = False
End If
If Not CheckBox2.Checked Then
args.IsValid = False
End If
End Sub
The ServerValidateEventArgs will allow you to specify if the user has met your criteria.
At the end of ServerValidate event, it will return the value set in the property IsValid to determine if it's valid or not.

Related

Clear Textbox with Regular Expression Validator

I Got a text box with a Regular Expression validator, to validate if my textbox is numeric.
here's the code :
<asp:TextBox ID="txtAmount" runat="server" CssClass="TextBoxCls"></asp:TextBox>
<asp:RegularExpressionValidator runat="server" ID="valNumbersOnly" ControlToValidate="txtAmount"
SetFocusOnError="true" Display="Dynamic" ErrorMessage="Please enter a numbers only in text box."
Font-Bold="true" ForeColor="Red" ValidationExpression="(^([0-9 ]*|\d*\d{1}?\d*)$)">
</asp:RegularExpressionValidator>
and , if the user accidentally input the wrong data , it'll show the Error Like This :
and i give the user, a clear function to clear all the textbox : with kind of this function :
Public Sub ClearTextBox(ByVal root As Control)
For Each ctrl As Control In root.Controls
ClearTextBox(ctrl)
If TypeOf ctrl Is TextBox Then
CType(ctrl, TextBox).Text = String.Empty
End If
Next ctrl
End Sub
Protected Sub btnClr_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnClr.Click
ClearTextBox(Me)
dropResponse.SelectedIndex = 0
FillData()
End Sub
but , the amount is not cleared, it still show the error. why it still happen?
If you are providing this through another button on the same form it won't ever hit the code-behind.
If you want a button on a validated form that needs to fire regardless of whether the other controls have validated, put it in a separate validation group:
<asp:Button runat="server" ID="btnClr" Text="Clear form" OnClick="btnClr_Click" ValidationGroup="unvalidatedControls" />
Alternatively, put a validation group on your controls that need validating and also the button that submits the form:
<asp:TextBox ID="txtAmount" runat="server" CssClass="TextBoxCls" ValidationGroup="validatedControls"></asp:TextBox>
<asp:RegularExpressionValidator runat="server" ID="valNumbersOnly" ControlToValidate="txtAmount"
SetFocusOnError="true" Display="Dynamic" ErrorMessage="Please enter a numbers only in text box."
Font-Bold="true" ForeColor="Red" ValidationExpression="(^([0-9 ]*|\d*\d{1}?\d*)$)"
ValidationGroup="validatedControls">
</asp:RegularExpressionValidator>
<asp:Button runat="server" ID="btnSubmit" Text="Submit Form" ValidationGroup="validatedControls" />
You could put a ValidationGroup attribute on both your clear button and the main form, as long as they're different, the clear button will work just fine.
Some documentation on Validation Groups: http://msdn.microsoft.com/en-us/library/ms227424.aspx
I suspect that the textbox is contained in a panel or another container control. Only the toplevel controls of a page are available in the controls collection of the page.
I would suggest to change the parameter of the call to ClearTextBox with the correct container control.

How to determine which button caused postback

I have 2 button controls. When I click one i'm trying to determine which one caused a postback in the page load. How to do determine this?
What about using CommandName and CommandArgument has shown in this example. This way you can have just one handler.
<asp:Button id="Button1"
Text="Sort Ascending"
CommandName="Sort"
CommandArgument="Ascending"
OnCommand="CommandBtn_Click"
runat="server"/>
<asp:Button id="Button2"
Text="Sort Descending"
CommandName="Sort"
CommandArgument="Descending"
OnCommand="CommandBtn_Click"
runat="server"/>
Do you come from a Classic ASP background? When I first used ASP.NET, the same question occurred to me.
Consider an alternative approach:
Rather than detect the postback in the Form_Load, and then figure out what triggered it, create a specific event handler for each of your buttons. This is the whole point of Web Forms - so you can develop apps in very similar ways as you would Windows applications.
Really input with type button sends its value within post request. For example if you have you'll get in Post button-name=Quote like it's simple text input. So you can just check if post contains value for the button using code like following (sorry for my vb):
Dim isQuote As Boolean = HttpContext.Current.Request.Form(SubmitQuote.UniqueID) IsNot Nothing
so if it's not Nothing (null) then post has been sent by SubmitQuote button.
BTW for me HttpContext.Current.Request("__EVENTTARGET") didn't work either.
In my implementation there are several forms on my page; if a post-back was triggered by certain button controls further operations are necessary.
The controls are of the following type, which do not populate Request["__EVENTTARGET"]
Button (at the root of the form)
Image Button (nested within a Datagrid)
I determine if the following button controls instigated the post-back, by reviewing that the UniqueID of the control was passed to the form request within the Page_Load sub:
- ASP.NET:
<asp:Button ID="Button1" runat="server" />
<asp:Button ID="Button2" runat="server" />
To simply handle whether the following nested image button instigated the post-back I take advantage of the OnClientClick attribute which calls to a javascript function that will populate the value of a supplementary hidden field control with the UniqueID of the instigating control, then review the hidden control value similarly in the Page_Lode sub:
- ASP.NET:
<script type="text/javascript">
function SetSource(SourceID) {
var hiddenField = document.getElementById("<%=HiddenField1.ClientID%>");
hiddenField.value = SourceID;
}
</script>
<asp:HiddenField ID="HiddenField1" runat="server" Value="" />
<asp:ImageButton ID="ImageButton1" runat="server" OnClientClick="SetSource(this.id)" />
The Page_Load would then implement by some means:
-VB.NET
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load
' ...
If Not Page.IsPostBack Then
If Not String.IsNullOrEmpty(Me.Page.Request.Form(Button1.UniqueID)) Then
' ...
ElseIf Not String.IsNullOrEmpty(Me.Page.Request.Form(Button2.UniqueID)) Then
' ...
ElseIf Not Me.Page.Request.Form(HiddenField1.UniqueID) Is Nothing _
And Not String.IsNullOrEmpty(Me.Page.Request.Form(HiddenField1.UniqueID)) Then
' ...
HiddenField1.Value = String.Empty
Else
' ...
End If
End If
End Sub
on page load check this
String ButtonID = Request["__EVENTTARGET"];

CustomValidator not working (asp.net vb)

I am using the CustomValidator for the first time but it doesn't seem to be firing DateExpireRequired_ServerValidate and just runs the code in the Click action.
Been bugging me for a couple hours now! can anyone see a problem with what im doing?
The DropDownList in my code below is populated using Roles.GetAllRoles()
ASP.NET
<asp:Label ID="lUserRole" runat="server" AssociatedControlID="tUserRole">User Role:</asp:Label>
<asp:DropDownList ID="tUserRole" runat="server" CausesValidation="True">
</asp:DropDownList>
<asp:Label ID="lDateExpire" runat="server" AssociatedControlID="tDateExpire">Date Expire:</asp:Label>
<asp:TextBox ID="tDateExpire" runat="server"></asp:TextBox>
<asp:CustomValidator ID="DateExpireRequired" runat="server"
ControlToValidate="tDateExpire" ErrorMessage="Date Expire is required for 'Users'." OnServerValidate="DateExpireRequired_ServerValidate"
ToolTip="Date Expire is required for 'Users'." CssClass="frmError"></asp:CustomValidator>
CODE BEHIND
Sub DateExpireRequired_ServerValidate(source As Object, args As System.Web.UI.WebControls.ServerValidateEventArgs)
If tUserRole.SelectedValue = "User" Then
If tDateExpire.Text <> "" Then
args.IsValid = False
Else
args.IsValid = True
End If
Else
args.IsValid = True
End If
End Sub
Thanks J.
You have Enabled="false" in your custom validator definition. I assume this is disabling that validator.
The answer was as in Menno van den Heuvel's comment above:
Do you have validateemptytext set to True? I see that you check for an empty string in your event handler, but the event handler won't be run if the bound control's value is empty.

VB - how to link up a Check_change to code behind for a checkbox

How do I enable a check_change for a checkbox in VB.
Here is what I have so far.
Code Behind:
Protected Sub CheckBoxCash_CheckedChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CheckBoxCash.CheckedChanged
Label1.Text = "Cash"
End Sub
Front end code:
<asp:Label ID="Label1" runat="server" Text="Empty"></asp:Label>
<asp:CheckBox ID="CheckBoxPoints" runat="server" Checked="True" />
It looks like you're not doing anything that specifically requires a postback here. In that case, I'd skip the postback entirely an do it more like this:
<asp:Label ID="Label1" runat="server" Text="Empty"></asp:Label>
<asp:CheckBox ID="CheckBoxPoints" runat="server" Checked="True" onclick="document.getElementById('Label1').value = 'Cash';" />
Of course, that's the simple version. Production code would also involve checking the label's clientid property in case these controls ever end up inside a naming container (like an asp:panel or gridview). I'd also look for a fallback for when javascript is not enabled, but in this case the Check_Changed server event depends on javascript to fire anyway.
I figured it out, I forgot to set the postback to true

Why won't my ASP.NET CustomValidator validate?

I must be doing something wrong. I can't seem to execute my CustomValidator's ServerValidate method.
I've got a Visual Basic ASP.NET page with a CustomValidator...
<asp:TextBox ID="TextBox1" runat="server" />
<asp:CustomValidator ID="CustomValidator1" runat="server"
ControlToValidate="TextBox1"
ErrorMessage="Friendly message goes here."
Display="Dynamic" />
<asp:Button ID="Button1" runat="server"
Text="Submit"
CausesValidation="True" />
For this test, I've got the validation set to always fail...
Sub CustomValidator1_ServerValidate(ByVal source As Object, ByVal args As System.Web.UI.WebControls.ServerValidateEventArgs) Handles CustomValidator1.ServerValidate
args.IsValid = False
End Sub
But, when the button is clicked, the CustomValidator1_ServerValidate() method never executes!
Protected Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Page.Validate()
If Page.IsValid Then
'it executes the code here!
End If
End Sub
Not even if I explicitly validate that control...
CustomValidator1.Validate() 'does nothing?
What am I doing wrong?
Add the property:
ValidateEmptyText="True"
Are you putting the validator control submit button in the same validation group?
Firstly, You seem to be missing the OnServerValidate attribute in your markup above.
Secondly, I would check to ensure that CustomValidator1_ServerValidate has been set up as an eventhandler for the ServerValidate event for Textbox1. I have had occasions where I have changed the name of the validate method in the markup and code-behind, but the IDE has not auto updated the subscribing method name passed to the eventhandler delegate
I know it's a daft question (or might sound like it!). But have you actually entered or changed the value in the textbox? I think the validator won't trigger without the contents of the textbox changing.

Resources