Make text box required depending on dropdown list value - c#

I have a dropdown list for the employees rank (e.g. Manager, Supervisor, Member, etc.) and a text box for Manager's/Supervisor's name. By default, the text box is not required so it could be empty.
However, if the dropdown list value is a "Member", then I need to make the text box required so empty value is not allowed.
I already have the requiredfieldvalidator in placed for the text box but I don't know how to disable/enable it depending on the value in dropdown list.
<ASP:DROPDOWNLIST id="drpLstEmRank" tabIndex="2" runat="server" WIDTH="321"></ASP:DROPDOWNLIST>
<asp:RequiredFieldValidator ID="valDrpLstEmRank" runat="server" ControlToValidate="drpLstEmRank"
Display="Dynamic" EnableClientScript="False" ErrorMessage="RequiredFieldValidator"
Font-Italic="True" Font-Names="Verdana" Font-Size="8pt" InitialValue="(Select Rank)">Please select a rank</asp:RequiredFieldValidator></TD>
<asp:RequiredFieldValidator ID="valTbHeadName" runat="server" ControlToValidate="tbHeadName"
Display="Dynamic" EnableClientScript="False" ErrorMessage="RequiredFieldValidator"
Font-Italic="True" Font-Names="Verdana" Font-Size="8pt">Please input a head's name</asp:RequiredFieldValidator>
<ASP:TEXTBOX id="tbHeadName" runat="server" WIDTH="415" HEIGHT="26" MaxLength="50"></ASP:TEXTBOX>

You can disable/enable the validator on the server side code in the Page_Load event as follows.
protected void Page_Load(object sender, EventArgs e)
{
valTbHeadName.Enabled = Request[drpLstEmRank.UniqueID] == "Member" ? true : false;
}
But dont forget to add the AutoPostBack="true" property to your dropdown list for the employees rank. Otherwise it wont work after changing the dropdownlist value.

Here is Client Side Solution
$("document").ready(function(){
$("drpLstEmRank").change(function(){
if(this.val() == "Member"){
EnableValidator("#valTbHeadName");
}
else{
DisableValidator("#valTbHeadName");
}
});
});
//Method to disable the validator
function DisableValidator(validatorId) {
var validator = $(validatorId);
ValidatorEnable(validator[0], false);
}
//Method to enable the validator
function EnableValidator(validatorId) {
var validator = $(validatorId);
ValidatorEnable(validator[0], true);
validator.hide(); //hides the error message
}

Related

asp.net How to set textbox length based on dropdownlist selection? C#

The drop down list contains three countries, How do you set the minimum number of digits to be entered in the postcode text-box based on what country is selected.
For example, if user selects America, then the postcode text-Box should be set to "[0-9]{6}". But if they select Australia then the post code should be "[0-9]{4}".
<asp:DropDownList ID="dropDownList" runat="server">
<asp:ListItem Value="-1">Country</asp:ListItem>
<asp:ListItem>America</asp:ListItem>
<asp:ListItem>Australia</asp:ListItem>
<asp:ListItem>Sweden</asp:ListItem>
</asp:DropDownList>
<asp:RequiredFieldValidator ID="RequiredFieldValidateCountry"
initialValue="-1"
ForeColor="Red"
runat="server"
ErrorMessage="Please choose Country"
ControlToValidate="dropDownList"/>
<asp:Label ID="Label1" runat="server" Text="PostCode"></asp:Label>
<asp:textbox id="TextBox1" runat="server" ></asp:textbox>
<asp:CustomValidator id="CustomValidator1" runat="server"
OnServerValidate="TextValidate"
ControlToValidate="TextBox1"
ErrorMessage="Invalid postcode.">
</asp:CustomValidator>
<asp:Button ID="BtnNext" runat="server" Text="Next" />
You can do this on the SelectedIndexChanged events of the dropdownlist. Set the AutoPostback to true in the dropdownlist write the similar described logic according to your need.
private void dropDownList_SelectedIndexChanged(object sender, System.EventArgs e)
{
//your logic, something like that
if(dropDownList.SelectedText =="America")
{
TextBox1.MaxLength= your value ...
}
}
<asp:DropDownList ID="dropDownList" runat="server" AutoPostback = "true">
EDIT:
You can check the total number of character of textbox with your predefined value.
int minlength = 5;
if(textbox1.text.length < minlength)
{
//Flag error on validation label
}
else
{
//your stuff
}
You also have client side events for the asp .net dropdown. You can set a javascript function to execute if the dropdown selection changes without posting back to the server. This will make the experience more streamlined and you can alter the min and max length directly with jquery.
You can do it like this:
DropDownList1.Attributes.Add("onChange", "return OnSelectedIndexChange();")

enabling/disabling validation from code behind c#

I have some asp code written for a form. One of the fields must have 3 types of validation, 2 of which are alway enabled, the other 2 must be "enabled" only if a peculiar value has been selected from a dropdownlist.
How am I supposed to achieve this task?
I have disabled the 2 extra validations by defaults and wold like to reactivate on dropdownlist specific selection.
I show you my code here.
ASP.NET code:
<tr>
<td class="style1">
<asp:Label ID="LabelPiva" runat="server" Text="Partita IVA" meta:resourcekey="LabelPiva" Font-Bold="True" />
</td>
<td>
<asp:TextBox ID="pivaTextBox" runat="server" Text='<%# Bind("piva") %>'
MaxLength="50" Width="400px" />
<asp:RequiredFieldValidator ID="RequiredPiva" runat="server"
ControlToValidate="pivaTextBox"
ErrorMessage="<%$ Resources:Resource, CampoObbligatorio %>" Display="Dynamic"
CssClass="little_text" />
<asp:CustomValidator ID="PivaEsistente" runat="server"
ErrorMessage="Partita IVA esistente nel database" meta:resourcekey="PivaEsistente"
ControlToValidate="pivaTextBox" CssClass="little_text" Display="Dynamic"
onservervalidate="PIVAEsistente_ServerValidate"></asp:CustomValidator>
<asp:RegularExpressionValidator ID="PivaSize" runat="server"
ControlToValidate="pivaTextBox" CssClass="little_text" Display="Dynamic"
ErrorMessage="Controllare la lunghezza della partita iva. 11 caratteri e solo numeri."
ValidationExpression="^[0-9]{11}$" Enabled="False" ValidationGroup="soloItalia">
</asp:RegularExpressionValidator>
<asp:CustomValidator ID="PivaErrata" runat="server"
ErrorMessage="Partita IVA non corretta. Controllare le cifre." meta:resourcekey="PivaErrata"
ControlToValidate="pivaTextBox" CssClass="little_text" Display="Dynamic"
onservervalidate="ValidatePI" Enabled="False" ValidationGroup="soloItalia"></asp:CustomValidator>
</td>
</tr>
The CustomValidator with id PivaErrata and the RegularExpressionValidator with id PivaSize must be fired only when dropdownlist hits the "it" value.
This is the code-behind in c# to intercept the value of the dropdownlist:
protected void nazioneDropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
DropDownList ddlProv = (DropDownList)FormUser.FindControl("provinciaDropDownList");
if ("it".Equals(ddl.SelectedValue))
{
ddlProv.Enabled = true;
}
else
{
ddlProv.SelectedIndex = 0;
ddlProv.Enabled = false;
}
}
As you can see, another dropdownlist gets enabled when that specific value "it" is fired in the nations dropdownlist.
I would like to activate the validations controls too.
I assigned a validationgroup to those 2 validations, but I am not sure how to "enable" them at once.
Any help?
Thank you very much.
you can use Enabled property of the Validation controls to enable or disable them.
Try This:
if (ddl.SelectedItem.ToString().Equals("it"))
{
ddlProv.Enabled = true;
//add these two statements to enable
PivaSize.Enabled=true;
PivaErrata.Enabled=true;
}
else
{
ddlProv.SelectedIndex = 0;
ddlProv.Enabled = false;
//add these two statements to disable
PivaSize.Enabled=false;
PivaErrata.Enabled=false;
}

If statement on dropDownList listItem

I need to add a condition to a DropDownList where a method can be executed by button click only if the user has selected a value different than the listItem (default value).
<asp:DropDownList ID="DropDownList1" runat="server" AppendDataBoundItems="True"
DataSourceID="SqlDataSource5"
DataTextField="proj_name" DataValueField="proj_name">
<asp:ListItem Text="Select a project to clone" Value="" />
</asp:DropDownList>
How can I structure an if condition to validate that the selected value is not the ListItem (default value)?
You can use asp.net delivered validation controls
Ex:
<asp:RequiredFieldValidator id="rfv1"
ControlToValidate="DropDownList1"
Display="Static"
ErrorMessage="* Select a value"
InitialValue="DefaultValueHere"
runat="server"
ValidationGroup="V1"/>
Then edit your button markup to use ValidationGroup
<asp:Button Id="button1" ValidationGroup="V1" .../>
In your codebehind button click code add this
protected void button1_onlick(Object sender, EventArgs e)
{
If(Page.IsValid)
{
// your existing code here
}
}
See sample code below
if (DropDownList1.SelectValue == "")
{
// Write your code here
}
you can also have:
if (DropDownList1.Text == "Select a project to clone")
{
// Write your code here
}

adding option to drop down list

I have a drop down list with multiple values. I have a list item named "Other". When selecting other I want to generate a text box with required field validator. I have written like this:
Markup:
<asp:DropDownList ID="dl_test_name" runat="server"
OnSelectedIndexChanged="SelectedIndexChanged"
Height="22px" Width="103px">
<asp:ListItem>Science</asp:ListItem>
<asp:ListItem>Maths</asp:ListItem>
<asp:ListItem>Other</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="tb_other" runat="server" Width="94px" Visible="False">
</asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator7" runat="server"
ControlToValidate="tb_other" ErrorMessage="*">
</asp:RequiredFieldValidator>
Code-behind:
protected void SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList dropDownList = (DropDownList)sender;
if (dropDownList.SelectedValue == "Other")
{
tb_other.Enabled = true;
tb_other.Text = string.Empty;
tb_other.Visible = true;
}
else
{
tb_other.Enabled = false;
tb_other.Text = dropDownList.SelectedValue;
}
}
but when selecting on any list item ,control doesn't go to SelectectedIndexChanged event. Only after reloading the page does it work.
What is the problem?
To make your DropDownList post back to the server you need to use the AutoPostback property, like this:
<asp:DropDownList ID="dl_test_name" runat="server"
OnSelectedIndexChanged="SelectedIndexChanged"
Height="22px" Width="103px" AutoPostBack="true">
Arathy, make AutopostBack property of dropdown to true in aspx

RadComboBox pre selection

First of all what I want to do is to pre select a value in my RadComboBox ,and if this value is not selected something else is selected then change the visibility to of some specific fields hidden.
My problem is that I'm able to make my pre select but somehow I can not change the status of my visibility for my specific fields when this pre selected value has changed.
What I have tired is to do it with a standard event OnSelectedIndexChanged but some how this is not triggering why so ever.. I have also added AutoPostBack=true as well as ViewStateMode=Enabled"
First my field's
Here comes my preslect as well here I would like to trigger the visibility change
<div class="formRowDiv">
<asp:Label ID="Activitylbl" runat="server" Text="Activity" CssClass="formLabel" />
<telerik:RadComboBox ID="rcbActivity" CssClass="rowForm" ViewStateMode="Enabled" runat="server" Width="260px" EmptyMessage="- Activity -"
DataTextField="ActivityId" DataValueField="ActivityId" AutoPostBack="true" OnSelectedIndexChanged="rcbActivity_SelectedIndexChanged">
</telerik:RadComboBox>
<asp:RequiredFieldValidator runat="server" Display="Dynamic" ControlToValidate="rcbActivity"
ErrorMessage="Can not be empty" CssClass="rowFormValidation" />
</div>
What I want to hide:
<div class="formRowDiv">
<asp:Label ID="ActivityDescription" runat="server" Text="ActivityDescription" CssClass="formLabel" Visible="false"/>
<telerik:RadTextBox runat="server" ID="rtbActivityDescription" Wrap="true" Height="50" TextMode="MultiLine" AutoPostBack="true" CssClass="rowForm" ReadOnly="true" Visible="false" />
</div>
How I do my pre selection :
In my databind method that is called in my Page_Load
I firrst loop and then do a pre select
foreach (Activity item in ctx.Activity.OrderBy(l =>l.Code))
{
rcbActivity.Items.Add(new RadComboBoxItem(item.FullActivity, item.ActivityId.ToString()));
if (rcbActivity.Items.FindItemByValue("4") != null)
{
rcbActivity.SelectedIndex = rcbActivity.Items.IndexOf(rcbActivity.Items.FindItemByValue("4"));
ActivityDescription.Visible = true;
rtbActivityDescription.Visible = true;
rtbActivityDescription.ReadOnly = false;
}
}
Here is how I would hide my Fields
protected void rcbActivity_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
{
ActivityDescription.Visible = true;
rtbActivityDescription.Visible = true;
rtbActivityDescription.ReadOnly = false;
}
In case your controls are in an update panel then try removing it if the update panel is not so important and see if the changes u make to the controls in the server side are getting affected properly

Categories

Resources