ASP.NET - Control dropdownlist postback programmatically - asp.net

I have two dropdownlists on my form-ddl1 and ddl2. They together determine the visibility of a textbox -txt1. For that I do this check:
if (ddl1.SelectedIndex==2 && ddl2.SelectedIndex>2)
{
if (!txt1.Visible)
{txt1.Visible=true;// And then I want to call postback}
}
else
{
if (txt1.Visible)
{txt1.Visible=false;// And then I want to call postback}
}
As you can see, I want to post the page to server only if the above condions are true. The code above is triggered on SelectedIndexChanged event of the both dropdownlists. How can I or is it possible to achieve upon a condition?

I am not sure if i understand your problem but you want to achieve postback only if certain condition is met. you can hook up a javascript function on both dropdown onchange="return onchange();" Set Autopostback = true;
function Onchange() {
var ddl1 = document.getElementById('<%= ddl1.ClientID %>');
var ddl2 = document.getElementById('<%= ddl2.ClientID %>');
var txtbox = document.getElementById('<%= txtbox.ClientID %>');
if (ddl1.selectedIndex == 2 && ddl2.selectedIndex > 2) {
txtbox.style.display = "inline";
__doPostBack(ddl1, '');
}
else {
txtbox.style.display = "none";
return false;
}
}
Aspx code should look like this.
<asp:DropDownList runat="server" AutoPostBack="true" ID="ddl1" onchange="return Onchange();"
OnSelectedIndexChanged="ddl1_SelectedIndexChanged">
<asp:ListItem Text="text1" />
<asp:ListItem Text="text2" />
<asp:ListItem Text="text3" />
<asp:ListItem Text="text4" />
</asp:DropDownList>
<asp:DropDownList runat="server" AutoPostBack="true" ID="ddl2" onchange="return Onchange();"
OnSelectedIndexChanged="ddl1_SelectedIndexChanged">
<asp:ListItem Text="text1" />
<asp:ListItem Text="text2" />
<asp:ListItem Text="text3" />
<asp:ListItem Text="text4" />
</asp:DropDownList>
<asp:TextBox runat="server" ID="txtbox" />
Tested it and it works...

If AutoPostBack = True, which it would have to be for your events to be firing just call a funciton when your condition is met. ASP.NET is always posting back, you just need to handle the condition, otherwise you have to handle the validation with JavaScript and manually post the page:
if (ddl1.SelectedIndex==2 && ddl2.SelectedIndex>2)
{
if (!txt1.Visible)
{
txt1.Visible=true;// And then I want to call postback
//dowork
}
}
else
{
if (txt1.Visible)
{
txt1.Visible=false;// And then I want to call postback
//do work
}
}

Related

Validation not firing in asp.net?

<td>Type:
</td>
<td>
<asp:DropDownList ID="ddltype" runat="server">
<asp:ListItem>---select---</asp:ListItem>
<asp:ListItem Text="Setter" Value="1">
</asp:ListItem>
<asp:ListItem Text="Getter" Value="2"></asp:ListItem>
</asp:DropDownList>
</td>
For this dropdownlist, I put validation like this
var ddltype = document.getElementById('<%=ddltype.ClientID%>');
var type = ddltype.options[ddltype.selectedValue].value;
if (type == 0) {
alert("Please Select setter/getter type.");
return false;
}
but it is not firing. How can I write this?
You should really get familiar with ASP.NET validators. Javascript can be disabled.
<asp:DropDownList ID="ddltype" runat="server" AutoPostBack="true">
<asp:ListItem>---select---</asp:ListItem>
<asp:ListItem Text="Setter" Value="1"></asp:ListItem>
<asp:ListItem Text="Getter" Value="2"></asp:ListItem>
</asp:DropDownList><br />
<asp:RequiredFieldValidator ID="reqType" runat="server"
InitialValue="---select---"
ControlToValidate="ddltype"
ErrorMessage="Required: Please select a Type"
Display="Dynamic"
CssClass="blah">
</asp:RequiredFieldValidator>
The InitialValue is important. Otherwise ---select--- would be a valid selection.
Note that i've also added AutoPostBack="true" to the DropDownList, maybe you want to postback immediately as soon as the user has selected an item.
Side-note: use a ValidationSummary with ShowMessageBox="true" and EnableClientScript="true" if you want to show the messages in a javascript alert.
Try this
var ddltype = document.getElementById('<%=ddltype.ClientID%>').text;
if (type == "---select---") {
alert("Please Select setter/getter type.");
return false;
}
Try this way ! but you can use asp.net validation control .
Any way ,my solution will validate two type ,for the dropdown selected vale or dropdown selected item
function Validate()
{
var e = document.getElementById('<%=ddltype.ClientID%>');
//if you need value to be compared then use
var strUser = e.options[e.selectedIndex].value;
//if you need text to be compared then use
var strUser1 = e.options[e.selectedIndex].text;
if(strUser==0) **//for text use if(strUser1=="---Select---")**
{
alert("Please Select setter/getter type.");
return false;
}
}
The below code has change your some code and working good for me
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Home.aspx.cs" Inherits="Home" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function validation() {
debugger;
var e = document.getElementById('<%=ddltype.ClientID%>');
var strUser1 = e.options[e.selectedIndex].value;
if (strUser1 == 0) {
alert("Please Select setter/getter type.");
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<table>
<tr>
<td>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClientClick="validation();" OnClick="btnSave_Click" />
<asp:DropDownList ID="ddltype" runat="server">
<asp:ListItem Text="--Select--" Value="0"></asp:ListItem>
<asp:ListItem Text="Setter" Value="1">
</asp:ListItem>
<asp:ListItem Text="Getter" Value="2"></asp:ListItem>
</asp:DropDownList>
</td>
</tr>
</table>
<div>
</div>
</form>
</body>
</html>
and see this line
<asp:ListItem Text="--Select--" Value="0"></asp:ListItem>
But you missed set value in that item , So it's get error, Now set value 0 in that line , and now your code working (See my sample code), Or you need to use .text and check the condition for
if(strUser1=="---Select---")
{
//alert
}

Custom validation javascript function always returns the drop down list's selected value as 0

On my page I have a text box that uses a custom validator:
<asp:CustomValidator ID="cv_Question" ControlToValidate="tb_Question" runat="server" ErrorMessage="*" OnServerValidate="ValidateQuestion" ClientValidationFunction="CheckQuestion" ForeColor="#FF0000" ValidationGroup="CreateUser"></asp:CustomValidator>
The client side validation script that I would like to use always returns 0 for the drop down list SelectedValue, even when the drop down list index has already changed.
I set the drop down list default index to 0 with !Page.IsPostBack
Here is the drop down list:
<asp:DropDownList ID="ddl_Question" runat="server" EnableViewState="true" AutoPostBack="true" onselectedindexchanged="ddl_Question_SelectedIndexChanged">
<asp:ListItem Selected="False" Text="Select a question" Value="0"></asp:ListItem>
<asp:ListItem Selected="False" Text="What was the first movie I ever saw?" Value="1"></asp:ListItem>
<asp:ListItem Selected="False" Text="What is the middle name of my oldest child?" Value="2"></asp:ListItem>
<asp:ListItem Selected="False" Text="In what city was my father born?" Value="3"></asp:ListItem>
<asp:ListItem Selected="False" Text="Who was my favourite cartoon character as a child?" Value="4"></asp:ListItem>
<asp:ListItem Selected="False" Text="What is my mother's middle name?" Value="5"></asp:ListItem>
<asp:ListItem Selected="False" Text="In what year did I meet my significant other?" Value="6"></asp:ListItem>
<asp:ListItem Selected="False" Text="What was my first pet's name?" Value="7"></asp:ListItem>
<asp:ListItem Selected="False" Text="First name of the maid of honour at my wedding?" Value="8"></asp:ListItem>
<asp:ListItem Selected="False" Text="First name of my best friend in elementary school?" Value="9"></asp:ListItem>
<asp:ListItem Selected="False" Text="Name of my all-time favourite movie character?" Value="10"></asp:ListItem>
<asp:ListItem Selected="False" Text="Create a question" Value="11"></asp:ListItem>
</asp:DropDownList>
Here is the client side validation:
<script type="text/javascript" language="javascript">
function CheckQuestion(sender, args)
{
var Question = args.Value.toString();
<% if(Convert.ToInt32(ddl_Question.SelectedValue) == 11)
{ %>
if (Question != "" && Question != null)
{
args.IsValid = true;
return;
}
else
{
args.IsValid = false;
return;
}
<% }
else
{ %>
alert(<%= Convert.ToInt32(ddl_Question.SelectedValue)%>);
args.IsValid = true;
return;
<% } %>
}
</script>
I only want to validate the tb_Question if the user has selected "Create a question" from the ddl_Question.
EDIT:
Here is my SelectedIndexChanged method. The tb_Question is made visible when the user selects "Create a question". This happens before any validation occurs.
protected void ddl_Question_SelectedIndexChanged(object sender, EventArgs e)
{
if (Convert.ToInt32(ddl_Question.SelectedValue) == 11)
{
Question.Visible = true;
}
else
{
Question.Visible = false;
}
}
Well my recommendation is to use simple JavaScript
So instead of doing that, use JavaScript and maybe jQuery like this
jQuery Nuget: https://nuget.org/packages/jQuery
<script type="text/javascript" src="Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript" language="javascript">
function CheckQuestion(sender, args)
{
var Question = args.Value.toString();
var questionID = '<%= this.ddl_Question.ClientID %>';
var currentQuestion = $("#" + questionID).val();
if (currentQuestion == '11')
{
if (Question != "" && Question != null)
{
args.IsValid = true;
return;
}
else
{
args.IsValid = false;
return;
}
}
else
{
alert(currentQuestion);
args.IsValid = true;
return;
}
}
</script>
The issue is more likely in the Convert.ToInt32 call since this utility method returns zero when the value passed to it is null (you can check MSDN to validate this. http://msdn.microsoft.com/en-us/library/sf1aw27b.aspx) The SelectedValue property is very likely null at this point even though the selected index is zero. Try setting the SelectedValue programmatically and see I that makes any difference.

Customvalidator: Check if radiobuttonlist contains a selected item

I have a radiobuttonlist with two items, Yes or No. The radiobuttonlist control has a customvalidator that needs a servervalidation function and a javascript clientvalidationfunction. Could you help me? The function in this message works but only when i actually have choosen one of the two listitems, when no listitem is selected the validation skips my radiobuttonlist control.
function ValidateRadioButtonList(source, arguments) {
var RBL = document.getElementById(source.controltovalidate);
var radiobuttonlist = RBL.getElementsByTagName("input");
var counter = 0;
var atLeast = 1
for (var i = 0; i < radiobuttonlist.length; i++) {
if (radiobuttonlist[i].checked) {
counter++;
}
}
if (atLeast = counter) {
arguments.IsValid = true;
return arguments.IsValid;
}
arguments.IsValid = false;
return arguments.IsValid;
}
EDIT: Relevant code from comments
<asp:Button ID="btnSubmit" runat="server" Text="Submit" CssClass="btnNormal"
CausesValidation="True" />
<asp:CustomValidator runat="server"
ClientValidationFunction="ValidateRadioButtonList"
OnServerValidate="RadioButtonListServerValidation" ID="cvRadioButtonList"
Font-Bold="True" Font-Size="Medium" ErrorMessage="Business critical"
ControlToValidate="rblBusinessCritical">*</asp:CustomValidator>
<asp:RadioButtonList ID="rblBusinessCritical" runat="server" RepeatLayout="Flow"
RepeatDirection="Horizontal" TabIndex="4">
<asp:ListItem Text="Yes" Value="1" />
<asp:ListItem Text="No" Value="0" />
</asp:RadioButtonList>
Code Behind:
Public Sub RadioButtonListServerValidation(ByVal sender As Object, _
ByVal args As ServerValidateEventArgs)
If rblBusinessCritical.SelectedValue = "-1" Then
args.IsValid = False
cvRadioButtonList.ErrorMessage = "Business critical needed"
Exit Sub
Else
args.IsValid = True
End If
End Sub
Have you set the ValidateEmptyText Property of the CustomValidator to true?
edit:
Have you set the CausesValidation Property of your Submit-Button/RadioButtonList to true?
Please provide some code from your aspx-page.
Here is another javascript clientvalidation function i have tried:
function ValidateRadioButtonList(source, arguments) {
var RBL = document.getElementById(source.controltovalidate);
var radio = RBL.getElementsByTagName("input");
var isChecked = false;
for (var i = 0; i < radio.length; i++) {
if (radio[i].checked) {
isChecked = true;
break;
}
}
if (!isChecked) {
alert("Please select an item");
arguments.IsValid = false;
}
arguments.IsValid = true;
}
Do you need to use client-side?
Here is a server-side solution...
<asp:RadioButtonList id="radTerms" runat="server">
<asp:listitem id="optDisagree" runat="server" value="Disagree" selected="true">I don't agree</asp:ListItem>
<asp:listitem id="optAgree" runat="server" value="Agree">I agree</asp:ListItem>
</asp:RadioButtonList>
<asp:CustomValidator Display="Dynamic" ErrorMessage="You have to agree to the terms and conditions" ID="cmpTerms" ControlToValidate="radTerms" SetFocusOnError="true" runat="server" OnServerValidate="cmpTermsAccepted_ServerValidate">*</asp:CustomValidator>
CodeBehind:
protected void cmpTermsAccepted_ServerValidate(Object source, System.Web.UI.WebControls.ServerValidateEventArgs args)
{
args.IsValid = (args.Value == "Agree");
}
That should work. Trying taking the control to validate property off the customer validator.
<asp:RadioButtonList ID="LocationAccurateRBL" CssClass="radioButtonList" RepeatDirection="Horizontal" RepeatColumns="4" RepeatLayout="Flow" runat="server">
<asp:ListItem Text="Yes" Value="1" />
<asp:ListItem Text="No" Value="0" />
</asp:RadioButtonList>
<asp:CustomValidator runat="server" ID="CheckBoxRequired" EnableClientScript="true" ControlToValidate="LocationAccurateRBL"
ClientValidationFunction="LocationAccurate_ClientValidate" ValidateEmptyText="true"
Text="*" ForeColor="Red" ErrorMessage="Please let us know if the location is accurate" SetFocusOnError="true" ValidationGroup="CreateVG" />
And the script, is much shorter because of jquery. This will do what you want.
<script>
function LocationAccurate_ClientValidate(sender, e) {
e.IsValid = $("#<%=LocationAccurateRBL.ClientID%> > input").is(':checked');
}
</script>

How to prevent ajax toolkit DropDownExtender from closing on click?

I have the code below to implement a dropdownlist with checkboxes. My problem is that every time i click a checkbox the dropdownlist closes and i need to reopen it to select more checkboxes. How do i make it so the dropdownlist dosn't close until i click off of it?
<asp:Panel ID="pnl_Items" runat="server" BorderColor="Aqua" BorderWidth="1">
<asp:CheckBoxList ID="cbl_Items" runat="server">
<asp:ListItem Text="Item 1" />
<asp:ListItem Text="Item 2" />
<asp:ListItem Text="Item 3" />
</asp:CheckBoxList>
</asp:Panel>
<br />
<asp:TextBox ID="tb_Items" runat="server"></asp:TextBox>
<ajax:DropDownExtender ID="TextBox1_DropDownExtender"
runat="server"
DynamicServicePath=""
Enabled="True"
DropDownControlID="pnl_Items" on
TargetControlID="tb_Items">
</ajax:DropDownExtender>
i prefer not altering AjaxControlToolkit. As follows:
$(document).ready(function() {
$('input[type=checkbox], label').click(function(e){
if (!e) var e = window.event;
e.cancelBubble = true;
if (e.stopPropagation)e.stopPropagation();
});
});
change jquery selector to your checkboxes!
I was able to get the desired behavior by adding the following javascript that I found on this post.
var DDE;
function pageLoad()
{
DDE = $find('<%= TextBox1_DropDownExtender.ClientID %>');
DDE._dropWrapperHoverBehavior_onhover();
$get('<%= pnl_Items.ClientID %>').style.width = $get('<%= tb_Items.ClientID %>').clientWidth;
if (DDE._dropDownControl) {
$common.removeHandlers(DDE._dropDownControl, DDE._dropDownControl$delegates);
}
DDE._dropDownControl$delegates = {
click: Function.createDelegate(DDE, ShowMe),
contextmenu: Function.createDelegate(DDE, DDE._dropDownControl_oncontextmenu)
}
$addHandlers(DDE._dropDownControl, DDE._dropDownControl$delegates);
}
function ShowMe() {
DDE._wasClicked = true;
}
You will need to get the Ajax control toolkit source code and modify the DropDownExtender to behave the way you want it to. Each control has its own folder with all the files related to it's ability to function within.
Recompile, drop the new dll into your project.

How to validate a user chose at least one checkbox in a CheckBoxList?

I've got a CheckBoxList control that I want to require the user to check at least ONE box, it does not matter if they check every single one, or 3, or even just one.
In the spirit of asp.net's validation controls, what can I use to enforce this? I'm also using the Ajax validation extender, so it would be nice if it could look like other controls, and not some cheesy server validate method in the codebehind.
<asp:CheckBoxList RepeatDirection="Horizontal" RepeatLayout="Table" RepeatColumns="3" ID="ckBoxListReasons" runat="server">
<asp:ListItem Text="Preliminary Construction" Value="prelim_construction" />
<asp:ListItem Text="Final Construction" Value="final_construction" />
<asp:ListItem Text="Construction Alteration" Value="construction_alteration" />
<asp:ListItem Text="Remodel" Value="remodel" />
<asp:ListItem Text="Color" Value="color" />
<asp:ListItem Text="Brick" Value="brick" />
<asp:ListItem Text="Exterior Lighting" Value="exterior_lighting" />
<asp:ListItem Text="Deck/Patio/Flatwork" Value="deck_patio_flatwork" />
<asp:ListItem Text="Fence/Screening" Value="fence_screening" />
<asp:ListItem Text="Landscape - Front" Value="landscape_front" />
<asp:ListItem Text="Landscape - Side/Rear" Value="landscape_side_rear" />
<asp:ListItem Text="Other" Value="other" />
</asp:CheckBoxList>
It's easy to do this validation server side, but I am assuming you want to do it client side?
JQuery can do this very easily as long as you have something that all checkbox controls have in common to use as a selector such as class (CssClass on your .NET control). You can make a simple JQuery function and connect it to a ASP.NET custom validator. Remember if you do go the custom validator route to make sure you check it server side as well in case javascript is not working, you don't get a free server side check like the other .NET validators.
For more information on custom validators check out the following links: www.asp.net and
MSDN
You don't need to use JQuery, it just makes the javascript function to iterate and look at all your checkbox controls much easier but you can just use vanilla javascript if you like.
Here is an example I found at: Link to original
<asp:CheckBoxList ID="chkModuleList"runat="server" >
</asp:CheckBoxList>
<asp:CustomValidator runat="server" ID="cvmodulelist"
ClientValidationFunction="ValidateModuleList"
ErrorMessage="Please Select Atleast one Module" ></asp:CustomValidator>
// javascript to add to your aspx page
function ValidateModuleList(source, args)
{
var chkListModules= document.getElementById ('<%= chkModuleList.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;
}
Side Note: JQuery is just a little js file include you need to add to your page. Once you have it included you can use all the JQuery you like. Nothing to install and it will be full supported in the next version of Visual Studio I think.
Here's a cleaner jQuery implementation that allows one ClientValidationFunction for any number of CheckBoxList controls on a page:
function ValidateCheckBoxList(sender, args) {
args.IsValid = false;
$("#" + sender.id).parent().find("table[id$="+sender.ControlId+"]").find(":checkbox").each(function () {
if ($(this).attr("checked")) {
args.IsValid = true;
return;
}
});
}
Here's the markup:
<asp:CheckBoxList runat="server"
Id="cblOptions"
DataTextField="Text"
DataValueField="Id" />
<xx:CustomValidator Display="Dynamic"
runat="server"
ID="cblOptionsValidator"
ControlId="cblOptions"
ClientValidationFunction="ValidateCheckBoxList"
ErrorMessage="One selection required." />
And finally, the custom validator that allows the client function to retrieve the target control by ID:
public class CustomValidator : System.Web.UI.WebControls.CustomValidator
{
public string ControlId { get; set; }
protected override void OnLoad(EventArgs e)
{
if (Enabled)
Page.ClientScript.RegisterExpandoAttribute(ClientID, "ControlId", ControlId);
base.OnLoad(e);
}
}
You can use a CustomValidator for that with a little bit of javascript.
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Select at least one"
ClientValidationFunction="checkCheckBoxList"></asp:CustomValidator>
<script type="text/javascript">
function checkCheckBoxList(oSrc, args) {
var isValid = false;
$("#<%= CheckBoxList1.ClientID %> input[type='checkbox']:checked").each(function (i, obj) {
isValid = true;
});
args.IsValid = isValid;
}
</script>
And for a RadioButtonList
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Select at least one" ClientValidationFunction="checkRadioButtonList"></asp:CustomValidator>
<script type="text/javascript">
function checkRadioButtonList(oSrc, args) {
if ($("input[name='<%= RadioButtonList1.UniqueID %>']:checked").val() == null) {
args.IsValid = false;
} else {
args.IsValid = true;
}
}
</script>
Here is another solution that may be considered via Dado.Validators on GitHub.
<asp:CheckBoxList ID="cblCheckBoxList" runat="server">
<asp:ListItem Text="Check Box (empty)" Value="" />
<asp:ListItem Text="Check Box 1" Value="1" />
<asp:ListItem Text="Check Box 2" Value="2" />
<asp:ListItem Text="Check Box 3" Value="3" />
</asp:CheckBoxList>
<Dado:RequiredFieldValidator runat="server" ControlToValidate="cblCheckBoxList" ValidationGroup="vlgSubmit" />
Example codebehind.aspx.cs
btnSubmit.Click += (a, b) =>
{
Page.Validate("vlgSubmit");
if (Page.IsValid) {
// Validation Successful
}
};
https://www.nuget.org/packages/Dado.Validators/
Ref: Check if a checkbox is checked in a group of checkboxes in clientside
We can achieve this by C# also
bool Item_selected = false;
foreach (ListItem item in checkbox.Items)
{
if (item.Selected == true)
{
Item_selected = true;
}
}
if (!Item_selected )
{
//your message to user
// message = "Please select atleast one checkbox";
}
Loop through each of the items in ckBoxListReasons. Each item will be of type 'ListItem'.
The ListItem will have a property called 'Selected' that is a boolean. It's true when that item is selected. Something like:
Dim bolSelectionMade As Boolean = False
For Each item As ListItem in ckBoxListReasons.Items
If item.Selected = True Then
bolSelectionMade = True
End If
Next
bolSelectionMade will be set to true if the user has made at least one selection. You can then use that to set the Valid state of any particular validator control you like.

Resources