Jump to content
kreplech

CustomValidator

Recommended Posts

Hello All,Quick question...In a DropDown list I have a choice "Other" - I'd like to alter the style of a text-box (to display:block) when "Other" is selected. If the "Other" textbox is empty when the form is submitted, I'd like the error message to display.So, as far as I can tell, I'll need a custom validator that both checks the value of the dropdown list to see if "Other" has been selected AND I will need to determine whether or not the user has entered a value for the "Other" textbox.Can somebody point me in the right direction? I'm new to .NET and not quite sure how to put this theory to action...(It would also be helpful if somebody could help me out with the .NET equivalent of the following html/java script:<select onchange="java script: showTextbox();">....<script language="javascript"> function showTextbox() { document.GetElementById...style.display=block; } </script>)Thanks,M

Share this post


Link to post
Share on other sites
[...]In a DropDown list I have a choice "Other" - I'd like to alter the style of a text-box (to display:block) when "Other" is selected. If the "Other" textbox is empty when the form is submitted, I'd like the error message to display [...]
The dropdownlist is a server control and the standard way is to use the server event handler:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e){	if (DropDownList1.SelectedValue == "Other")	{		TextBox1.Visible = true;	}	else	{		TextBox1.Visible = false;	}}

which can be expressed more concisely as:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e){	TextBox1.Visible = (DropDownList1.SelectedValue == "Other");}

(If you're using VB not C#, adjust as necessary).Wasn't sure if you had further questions about the custom validator, but that should be kept separate from setting the textbox visibility anyway.EDIT: To use the above, you will need to set the dropdownlist's AutoPostBack property to true. If you want to do it client side that will be a different approach.Your custom validator could work as follows. Set its ControlToValidate property to be the dropdownlist, and then add the following event hander:

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args){	args.IsValid = (!(DropDownList1.SelectedValue == "Other" && TextBox1.Text.Trim().Length == 0));}

which can be expressed less concisely as:

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args){	args.IsValid = true;	if (DropDownList1.SelectedValue == "Other")	{		if (TextBox1.Text.Trim().Length == 0)		{			args.IsValid = false;		}	}}

Share this post


Link to post
Share on other sites

Thank you VERY much. As I said I'm new to this, but I look forward to when I'll be able to lend a hand...Thanks again,M

The dropdownlist is a server control and the standard way is to use the server event handler:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e){	if (DropDownList1.SelectedValue == "Other")	{		TextBox1.Visible = true;	}	else	{		TextBox1.Visible = false;	}}

which can be expressed more concisely as:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e){	TextBox1.Visible = (DropDownList1.SelectedValue == "Other");}

(If you're using VB not C#, adjust as necessary).Wasn't sure if you had further questions about the custom validator, but that should be kept separate from setting the textbox visibility anyway.EDIT: To use the above, you will need to set the dropdownlist's AutoPostBack property to true. If you want to do it client side that will be a different approach.Your custom validator could work as follows. Set its ControlToValidate property to be the dropdownlist, and then add the following event hander:

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args){	args.IsValid = (!(DropDownList1.SelectedValue == "Other" && TextBox1.Text.Trim().Length == 0));}

which can be expressed less concisely as:

protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args){	args.IsValid = true;	if (DropDownList1.SelectedValue == "Other")	{		if (TextBox1.Text.Trim().Length == 0)		{			args.IsValid = false;		}	}}

Share this post


Link to post
Share on other sites

OK - The plot thickens. Turns out that I'm really trying to toggle the visibility of a TemplateField within a DetailsView:<asp:TemplateField HeaderText="Unit (Other)" HeaderStyle-Font-Bold="true" Visible="False"> <InsertItemTemplate> <asp:TextBox runat="server" ID="Unit_Other" style="width:95px;"></asp:TextBox> </InsertItemTemplate></asp:TemplateField>when OnSelectedIndexChanged="Set_Unit":protected void Set_Unit(object sender, EventArgs e) { DropDownList ddl = null; TextBox Unit_Other = null; ddl = (DropDownList)DetailsView1.FindControl("DropDownUnit"); Unit_Other = (TextBox)DetailsView1.FindControl("Unit_Other"); if (ddl.SelectedValue == "Other") { Unit_Other.Visible = true; } else { Unit_Other.Visible = false; } }but this doesn't work. how to toggle that templatefield?Thanks,M

Share this post


Link to post
Share on other sites
OK - The plot thickens. Turns out that I'm really trying to toggle the visibility of a TemplateField within a DetailsView:<asp:TemplateField HeaderText="Unit (Other)" HeaderStyle-Font-Bold="true" Visible="False"> <InsertItemTemplate> <asp:TextBox runat="server" ID="Unit_Other" style="width:95px;"></asp:TextBox> </InsertItemTemplate></asp:TemplateField>when OnSelectedIndexChanged="Set_Unit":protected void Set_Unit(object sender, EventArgs e) { DropDownList ddl = null; TextBox Unit_Other = null; ddl = (DropDownList)DetailsView1.FindControl("DropDownUnit"); Unit_Other = (TextBox)DetailsView1.FindControl("Unit_Other"); if (ddl.SelectedValue == "Other") { Unit_Other.Visible = true; } else { Unit_Other.Visible = false; } }but this doesn't work. how to toggle that templatefield?Thanks,M
The DetalsView's Fields collection is where the template fields can be found. To set the visibility of the first field, use index 0:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e){	DetailsView1.Fields[0].Visible = (((DropDownList)sender).SelectedValue == "Other");}

Share this post


Link to post
Share on other sites

this all makes good sense... but its just not working out for some reason. i appreciate you hanging in there...the entire detailsview:

<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" DataKeyNames="ID"			DataSourceID="ObjectDataSource2" DefaultMode="Insert" GridLines="None" CssClass="detailsview">			<Fields>				<asp:TemplateField HeaderText="Unit" HeaderStyle-Font-Bold="true">					<InsertItemTemplate>						<asp:DropDownList EnableViewState="false" runat="server" ID="DropDownUnit" OnSelectedIndexChanged="Set_Unit"							DataSourceID="ObjectDataSource3" DataTextField="Unit_Description" DataValueField="Unit_ID">						</asp:DropDownList>						<asp:RangeValidator MinimumValue="1" MaximumValue="20" Type="Integer" ValidationGroup="Insert_Group"							ControlToValidate="DropDownUnit" ID="RangeValidator1" runat="server" ErrorMessage="Please select a Unit"></asp:RangeValidator>											</InsertItemTemplate>				</asp:TemplateField>				<asp:TemplateField HeaderText="Unit (Other)" HeaderStyle-Font-Bold="true">					<InsertItemTemplate>						<asp:TextBox runat="server" ID="Unit_Other" style="width:110px;"></asp:TextBox>					</InsertItemTemplate>				</asp:TemplateField>				<asp:CheckBoxField DataField="Circulated" HeaderText="Circulated" SortExpression="Circulated"					HeaderStyle-Font-Bold="true" />				<asp:TemplateField HeaderText="Work Share" HeaderStyle-Font-Bold="true">					<InsertItemTemplate>						<asp:DropDownList runat="server" ID="DropDownShare">							<asp:ListItem Selected="True" Value="" Text="" />							<asp:ListItem Value="0">0</asp:ListItem>							<asp:ListItem Value="5">5</asp:ListItem>							<asp:ListItem Value="10">10</asp:ListItem>							<asp:ListItem Value="15">15</asp:ListItem>							<asp:ListItem Value="20">20</asp:ListItem>							<asp:ListItem Value="25">25</asp:ListItem>							<asp:ListItem Value="30">30</asp:ListItem>							<asp:ListItem Value="35">35</asp:ListItem>							<asp:ListItem Value="40">40</asp:ListItem>							<asp:ListItem Value="45">45</asp:ListItem>							<asp:ListItem Value="50">50</asp:ListItem>							<asp:ListItem Value="55">55</asp:ListItem>							<asp:ListItem Value="60">60</asp:ListItem>							<asp:ListItem Value="65">65</asp:ListItem>							<asp:ListItem Value="70">70</asp:ListItem>							<asp:ListItem Value="75">75</asp:ListItem>							<asp:ListItem Value="80">80</asp:ListItem>							<asp:ListItem Value="85">85</asp:ListItem>							<asp:ListItem Value="90">90</asp:ListItem>							<asp:ListItem Value="95">95</asp:ListItem>							<asp:ListItem Value="100">100</asp:ListItem>						</asp:DropDownList>						<asp:RequiredFieldValidator ValidationGroup="Insert_Group" ControlToValidate="DropDownShare"							ID="RequiredFieldValidator2" runat="server" ErrorMessage="This field is required"></asp:RequiredFieldValidator>					</InsertItemTemplate>				</asp:TemplateField>				<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True"					SortExpression="ID" Visible="false" />				<asp:CommandField ShowInsertButton="True" ValidationGroup="Insert_Group" />			</Fields></asp:DetailsView>

and here's the c#:

protected void Page_Load(object sender, EventArgs e)	{		DetailsView1.Fields[1].Visible = false;	}protected void Set_Unit(object sender, EventArgs e)	{		DetailsView1.Fields[1].Visible = (((DropDownList)sender).SelectedValue = "18");		DropDownList ddl = null;		DropDownList ddl2 = null;		TextBox Unit_Other = null;		ddl = (DropDownList)DetailsView1.FindControl("DropDownUnit");		ddl2 = (DropDownList)DetailsView1.FindControl("DropDownShare");		Unit_Other = (TextBox)DetailsView1.FindControl("Unit_Other");		//Add parameters to insert statement		ObjectDataSource2.InsertParameters.Add("APPLID", (string)(Session["RANDID"]));		ObjectDataSource2.InsertParameters.Add("Unit", ddl.SelectedValue);		ObjectDataSource2.InsertParameters.Add("Unit_Other", Unit_Other.Text);		ObjectDataSource2.InsertParameters.Add("Work_Share", ddl2.SelectedValue);		ObjectDataSource2.Update();	}

any ideas???thanks again,M

Share this post


Link to post
Share on other sites
this all makes good sense... but its just not working out for some reason. i appreciate you hanging in there [...]
A couple of things that would stop it working:
						<asp:DropDownList EnableViewState="false" runat="server" ID="DropDownUnit" OnSelectedIndexChanged="Set_Unit"							DataSourceID="ObjectDataSource3" DataTextField="Unit_Description" DataValueField="Unit_ID">						</asp:DropDownList>

The above needs AutoPostBack="True", or your sever event will not fire.And the line below needs to use "==" for the test, i.e., SelectedValue == "18"

DetailsView1.Fields[1].Visible = (((DropDownList)sender).SelectedValue = "18");

Share this post


Link to post
Share on other sites

still nothing. i don't have much more to add. i fixed the autopostback - and the == thing was just a product of testing (i'll try anything at this point). anyway, i appreciate your help.thanks again,M

Share this post


Link to post
Share on other sites
A couple of things that would stop it working:
						<asp:DropDownList EnableViewState="false" runat="server" ID="DropDownUnit" OnSelectedIndexChanged="Set_Unit"							DataSourceID="ObjectDataSource3" DataTextField="Unit_Description" DataValueField="Unit_ID">						</asp:DropDownList>

The above needs AutoPostBack="True", or your sever event will not fire.

Also, unless you are rebuilding "ObjectDataSource3", whatever that might be, on every page load, your DropDownList will not have any data bound to it because the ViewState is disabled for that control. And, according to the Page_Load method that you posted, it doesn't look like you are rebuilding it each time the page loads. You may have to enable ViewState to get this to work.

Share this post


Link to post
Share on other sites

I pasted your code into a new project, removed the databindings so I could just run it, and it works fine. The textbox becomes visible and invisible according to whether you select 18 in the dropdown.This hacked version is below for you to play with, copied straight from the working project:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server">    <title>Untitled Page</title></head><body>    <form id="form1" runat="server">        <div>        <asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" DataKeyNames="ID" DefaultMode="Insert" GridLines="None" CssClass="detailsview">            <Fields>                <asp:TemplateField HeaderText="Unit">                    <InsertItemTemplate>                        <asp:DropDownList EnableViewState="false" runat="server" ID="DropDownUnit" OnSelectedIndexChanged="Set_Unit"                            DataTextField="Unit_Description" DataValueField="Unit_ID" AutoPostBack="True">                            <asp:ListItem Value="1"></asp:ListItem>                            <asp:ListItem Value="18"></asp:ListItem>                            <asp:ListItem Value="25"></asp:ListItem>                        </asp:DropDownList>                        <asp:RangeValidator MinimumValue="1" MaximumValue="20" Type="Integer" ValidationGroup="Insert_Group"                            ControlToValidate="DropDownUnit" ID="RangeValidator1" runat="server" ErrorMessage="Please select a Unit"></asp:RangeValidator>                                            </InsertItemTemplate>                    <HeaderStyle Font-Bold="True" />                </asp:TemplateField>                <asp:TemplateField HeaderText="Unit (Other)">                    <InsertItemTemplate>                        <asp:TextBox runat="server" ID="Unit_Other" style="width:110px;"></asp:TextBox>                    </InsertItemTemplate>                    <HeaderStyle Font-Bold="True" />                </asp:TemplateField>                <asp:CheckBoxField DataField="Circulated" HeaderText="Circulated" SortExpression="Circulated" >                    <HeaderStyle Font-Bold="True" />                </asp:CheckBoxField>                <asp:TemplateField HeaderText="Work Share">                    <InsertItemTemplate>                        <asp:DropDownList runat="server" ID="DropDownShare">                            <asp:ListItem Selected="True" Value="" Text="" />                            <asp:ListItem Value="0">0</asp:ListItem>                            <asp:ListItem Value="5">5</asp:ListItem>                            <asp:ListItem Value="10">10</asp:ListItem>                            <asp:ListItem Value="15">15</asp:ListItem>                            <asp:ListItem Value="20">20</asp:ListItem>                            <asp:ListItem Value="25">25</asp:ListItem>                            <asp:ListItem Value="30">30</asp:ListItem>                            <asp:ListItem Value="35">35</asp:ListItem>                            <asp:ListItem Value="40">40</asp:ListItem>                            <asp:ListItem Value="45">45</asp:ListItem>                            <asp:ListItem Value="50">50</asp:ListItem>                            <asp:ListItem Value="55">55</asp:ListItem>                            <asp:ListItem Value="60">60</asp:ListItem>                            <asp:ListItem Value="65">65</asp:ListItem>                            <asp:ListItem Value="70">70</asp:ListItem>                            <asp:ListItem Value="75">75</asp:ListItem>                            <asp:ListItem Value="80">80</asp:ListItem>                            <asp:ListItem Value="85">85</asp:ListItem>                            <asp:ListItem Value="90">90</asp:ListItem>                            <asp:ListItem Value="95">95</asp:ListItem>                            <asp:ListItem Value="100">100</asp:ListItem>                        </asp:DropDownList>                        <asp:RequiredFieldValidator ValidationGroup="Insert_Group" ControlToValidate="DropDownShare"                            ID="RequiredFieldValidator2" runat="server" ErrorMessage="This field is required"></asp:RequiredFieldValidator>                    </InsertItemTemplate>                    <HeaderStyle Font-Bold="True" />                </asp:TemplateField>                <asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True"                    SortExpression="ID" Visible="False" />                <asp:CommandField ShowInsertButton="True" ValidationGroup="Insert_Group" />            </Fields></asp:DetailsView>                 </div>    </form></body></html>

using System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;public partial class _Default : System.Web.UI.Page{    protected void Page_Load(object sender, EventArgs e)    {        DetailsView1.Fields[1].Visible = false;    }    protected void Set_Unit(object sender, EventArgs e)    {        DetailsView1.Fields[1].Visible = (((DropDownList)sender).SelectedValue == "18");        DropDownList ddl = null;        DropDownList ddl2 = null;        TextBox Unit_Other = null;        ddl = (DropDownList)DetailsView1.FindControl("DropDownUnit");        ddl2 = (DropDownList)DetailsView1.FindControl("DropDownShare");        Unit_Other = (TextBox)DetailsView1.FindControl("Unit_Other");        //Add parameters to insert statement        //ObjectDataSource2.InsertParameters.Add("APPLID", (string)(Session["RANDID"]));        //ObjectDataSource2.InsertParameters.Add("Unit", ddl.SelectedValue);        //ObjectDataSource2.InsertParameters.Add("Unit_Other", Unit_Other.Text);        //ObjectDataSource2.InsertParameters.Add("Work_Share", ddl2.SelectedValue);        //ObjectDataSource2.Update();    }    protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)    {    }    protected void DetailsView1_ItemInserting(object sender, DetailsViewInsertEventArgs e)    {    }    protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)    {        DetailsView1.Fields[0].Visible = (((DropDownList)sender).SelectedValue == "Other");    }}

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...