Category Archives: CompareValidator

CompareValidator

[RESOLVED]javascript should work after Regular Expression Validatior

Hi all,

        I have a form named ChangePassword.aspx. Here I am having 3 text boxes, 1st one is for old password, 2nd is for new password and the 3rd one is for confirm password.

       

 <tr>
            <td align="left" class="nbdcontent" style="width: 143px; height: 19px">
                Enter old password</td>
            <td align="center" class="nbdcontent" style="width: 10px; height: 19px">
                :</td>
            <td align="left" style="width: 100px; height: 19px">
                <asp:TextBox ID="txtOldpass" runat="server" CssClass="mytextbox" TextMode="Password"></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvOldpass" runat="server" ControlToValidate="txtOldpass"
                    ErrorMessage="Please enter Old Password !">*</asp:RequiredFieldValidator></td>
        </tr>
        <tr>
            <td align="right" class="nbdcontent" style="height: 19px" colspan="3">
                         <asp:RegularExpressionValidator ID="Regex2" runat="server" ControlToValidate="txtNewPass"
    ValidationExpression="[a-z]+"
    ErrorMessage="Minimum 8 characters atleast 1 Alphabet, 1 Number and 1 Special Character" 
                             ForeColor="Red" >*</asp:RegularExpressionValidator>
            </td>
        </tr>
        <tr>
            <td align="left" class="nbdcontent" style="width: 143px; height: 19px">
                Enter new password</td>
            <td align="center" class="nbdcontent" style="width: 10px; height: 19px">
                :</td>
            <td align="left" style="width: 100px; height: 19px">
                <asp:TextBox ID="txtNewPass" runat="server" CssClass="mytextbox" 
                    TextMode="Password"></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvNpass" runat="server" ControlToValidate="txtNewPass"
                    ErrorMessage="Please enter New Password !">*</asp:RequiredFieldValidator></td>
        </tr>
        <tr>
            <td align="right" class="nbdcontent" style="height: 19px" colspan="3">
                         <asp:RegularExpressionValidator ID="Regex3" runat="server" ControlToValidate="txtNCpass"
    ValidationExpression="^(?=.*[A-Za-z])(?=.*d)(?=.*[$@$!%*#?&])[A-Za-zd$@$!%*#?&]{8,}$"
    ErrorMessage="Minimum 8 characters atleast 1 Alphabet, 1 Number and 1 Special Character" 
                             ForeColor="Red" >*</asp:RegularExpressionValidator>
            </td>
        </tr>
        <tr>
            <td align="left" class="nbdcontent" style="width: 143px; height: 19px">
                Confirm password</td>
            <td align="center" class="nbdcontent" style="width: 10px; height: 19px">
                :</td>
            <td align="left" style="width: 100px; height: 19px">
                <asp:TextBox ID="txtNCpass" runat="server" CssClass="mytextbox" 
                    TextMode="Password"></asp:TextBox>
                <asp:RequiredFieldValidator ID="rfvNCP" runat="server" ControlToValidate="txtNCpass"
                    ErrorMessage="Please enter confirm New  Password">*</asp:RequiredFieldValidator>
                <asp:CompareValidator ID="cvNPass" runat="server" ControlToCompare="txtNewPass" ControlToValidate="txtNCpass"
                    ErrorMessage="Password did not match !">*</asp:CompareValidator></td>
        </tr>
        <tr>
            <td align="left" class="nbdcontent" style="width: 143px; height: 19px">
            </td>
            <td align="center" class="nbdcontent" style="width: 10px; height: 19px">
            </td>
            <td align="left" style="width: 100px; height: 19px">
            </td>
        </tr>
        <tr>
            <td align="left" class="nbdcontent" style="width: 143px; height: 19px">
            </td>
            <td align="center" class="nbdcontent" style="width: 10px; height: 19px">
            </td>
            <td align="left" style="width: 100px; height: 19px">
                <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Update" />

Here I I have used RegularExpressionValidator  for password complexity. I am also encrypting the password word on client side.

below is my code for encrypting password.

<script type="text/javascript" src="../js/md5.js">  </script>
    <script type="text/javascript">

     function ChangePwd(salt) {

         var control = "<%=txtOldpass.ClientID %>";
         if (document.getElementById(control).value != "") {

             document.getElementById(control).value =
                    hex_md5(document.getElementById(control).value);

             document.getElementById(control).value =
                    hex_md5(document.getElementById(control).value + salt);
         }

         var control2 = "<%=txtNCpass.ClientID %>";
         if (document.getElementById(control2).value != "") {
         

             document.getElementById(control2).value =
                    hex_md5(document.getElementById(control2).value);
         }

         var control3 = "<%=txtNewPass.ClientID %>";
         if (document.getElementById(control3).value != "") {
           
             document.getElementById(control3).value =
                    hex_md5(document.getElementById(control3).value);
         }
     }
    </script>

and on page load

I am adding an attribute to the button

Button1.Attributes.Add("onclick", "return ChangePwd('" + salt.ToString() + "'); ToggleButton();");

The problem is :- as I click the button to change the password, it encrypt the entered string in the textboxes. As the password is encrypted now doesn’t meet the password complexity.

I want that, first it run the regular expression validator then it should encrypt the password.

Any Idea how to achieve this.

Hi demoninside,

Thanks for your post.

As for your problem, in fact, RegularExpressionValidator control validates the value of “txtNCpass” two times. The first time, when “txtNCpass” TextBox lose focus, RegularExpressionValidator control validates the value of “txtNCpass”. The second time, if
you click Button1, the page will refesh and RegularExpressionValidator control validates the value again. In this situation, encrypted password will not meet the password complexity.

To solve this problem, we could set IsValid property to true from behind code as below.

protected void Button1_Click(object sender, EventArgs e)
{
    Regex3.IsValid = true;
} 

Hope it will be helpful to you.

Best Regards,

Fei Han

[RESOLVED]Chosen javascript plugin and validator callout extender

Hi all,

I am working on a web page that perferms insert and update operations. I used
Chosen plugin
 to make my dropdownlists look more fancy and functional.  The insert/update area is a modal popup. Here is how my dropdowns look like in .aspx file:

<asp:DropDownList ID="DropDownListItems" runat="server" data-placeholder="-- Choose An Item --"
AutoPostBack="True" CssClass="chzn-select-deselect"
onselectedindexchanged="DropDownListItems_SelectedIndexChanged"
Width="300px">
<asp:ListItem Text="Please Select" Value="-1">
</asp:ListItem>
</asp:DropDownList>

<asp:CompareValidator ID="CompareValidator4" runat="server" ControlToValidate="DropDownListItems" Display="None" ErrorMessage="Please Select An Item" ForeColor="Red" Operator="NotEqual" ValidationGroup="InsertUpdate" ValueToCompare="-1"></asp:CompareValidator>

<ajaxToolkit:ValidatorCalloutExtender ID="ValidatorCallOutExtender1" runat="server" PopupPosition="Right" TargetControlID="CompareValidator4"></ajaxToolkit:ValidatorCalloutExtender>

I register a client script in every postback (in Page_Load) as:

protected void Page_Load(object sender, EventArgs e)
        {
            string Script = @"$('.chzn-select').chosen({no_results_text: 'No result found.',max_selected_options: 20}); $('.chzn-select-deselect').chosen({allow_single_deselect: true , no_results_text: 'No result found.' });";
            ScriptManager.RegisterStartupScript(Page, typeof(UpdatePanel), "JSCR", Script, true);

            BindDropDownListItems();
        }

If this registration is not done then the dropdownlists look as normal asp.net dropdownlist.

The problem is that when user does not select any item then validation callout extender shows in the top-left corner of the page.

However, I have other callout extenders tied to textboxes and they are shown normally, at the right sight of the textbox as expected.

Has anyone encounter this problem? Any help is greatly appreciated.

Thanks in advance.

Bydefault ValidatorCallout is displyed on left sode of control

To use this control, add an input field and a validator control as you normally would. Then add the ValidatorCallout and set its TargetControlID property to reference the validator control.

http://www.asp.net/AJAX/AjaxControlToolkit/Samples/ValidatorCallout/ValidatorCallout.aspx

To place the popupTable on the left side or the other place, we need to use the set_x/set_y method of the ValidatorCalloutExtender’s popupBehavior when the popup is shown
http://forums.asp.net/p/1286734/2488816.aspx#2488816 

http://forums.asp.net/t/1286247.aspx 

Or you can set the position of popup table dynamically by using  $find(‘ValidatorCalloutBehaviorId’)._popupTable.style.right

[RESOLVED]validating a CalendarExtender date against another CalendarExtender date

I have 2 CalendarExtenders and would like the 2nd

CalendarExtender date to be ‘GreaterThanEqual’ to the first one.

At the moment I get my validation error popping up for all dates entered!

Here’s what i have:

first text Box

<asp:TextBox ID="txtEnrolmentDate" runat="server" MaxLength="10"></asp:TextBox>  &nbsp;

2nd text box

   <asp:TextBox ID="txtDefferralDate" runat="server" MaxLength="10"></asp:TextBox> 

Validation:

  <asp:CompareValidator ID=" " 
                            runat="server" 
                            ErrorMessage="Deferral date cannot be before the enrolment date"
                          ControlToValidate="txtDefferralDate" 
                            Display="Dynamic" 
                              SetFocusOnError="True"
                             Operator="GreaterThanEqual" ValueToCompare="txtEnrolmentDate" 
                            ></asp:CompareValidator>

is it to do with the above validation being a string and its trying to compare it with a date?
But when I set my validator type to a ‘date’ it crashes – with this error:
ValueToCompare property of " " cannot be converted to type date.

So, do I need to create another box/label and convert my textbox: ‘txtEnrolmentDate’ into a date value and use this to validate against?
Or is there a quicker way of converting this string into a date within the validator:
‘cvDeferralDate’ ?
thanks.

<asp:CompareValidator ID="cmpStartDate" runat="server"
                        ControlToValidate="txtDefferralDate"
                        ErrorMessage="Start date cannot be less than today's date" 
                        Operator="GreaterThanEqual" Type="Date"
ValueToCompare="txtEnrolmentDate"></asp:CompareValidator>&nbsp;

thanks for the reply, but…

If I put type="Date", the page crashes with this error:
ValueToCompare property of " " cannot be converted to type date.

- due to txtDeferralDate – being in a textbox

Check this its Work for me fine

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <asp:CalendarExtender ID="CalendarExtender1" runat="server" TargetControlID="TextBox1">
            </asp:CalendarExtender>
            <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
             <asp:CalendarExtender ID="CalendarExtender2" runat="server" TargetControlID="TextBox2">
            </asp:CalendarExtender>


         
       
            <asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="CompareValidator" ControlToCompare="TextBox1" ControlToValidate="TextBox2" Type="Date" Operator="GreaterThanEqual"></asp:CompareValidator>
                <asp:Button ID="Button1" runat="server" Text="Button" />

thanks,

your code does indeed work but I think i must have something else going on, I’ve got other validation and having trouble getting it to work with other validation around it.

 

[RESOLVED]Disable future date in Ajax CalendarExtender

Dear all,

i am using Ajax Control toolkit version 4.1. and i need to restrict user from entering future date. also in my web app user can enter date manul in textbox associated with Ajax Calendar extender control. any demo any suggestion. i need it urgently.

thanks.

Calender1.EndDate =DateTime.Now.Date; // here you enter your future date

Or you can use this for furture end date limit

Calender1.EndDate = DateTime.Now.AddDays(90);;

Sorry dear EndDate  property is not available to me. i am using ‘CalendarExtender’ from Ajax toolkit

hey search this property on internet its work fine 

yourAjaxCalenderID.EndDate =DateTime.Now.Date

Download the demo program from given link

https://skydrive.live.com/?lc=24841#cid=2F22272220E37707&id=2F22272220E37707%21103

Program name is =CalenerDateLimit

Shoail, 

thanks for your demo. its good but when i plug it into my app it does not work and also i cannot restrict date if user enter date manally in textbox. might be because of difference in minor version of Ajax toolkit that i am using

Hi,

Please refer to the code as follow:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Calendar_limit.aspx.cs" Inherits="test7" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!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></title>

    <script type="text/javascript">
                function checkDate(sender, args) {
            if (sender._selectedDate < new Date()) {
                alert("You cannot select a day earlier than today!");
                sender._selectedDate = new Date();
                // set the date back to the current date
                sender._textbox.set_Value(sender._selectedDate.format(sender._format))
                        }

        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
    </asp:ToolkitScriptManager>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Date"/>
    <asp:CalendarExtender ID="CalendarExtender1" BehaviorID="CalendarExtender1" runat="server" TargetControlID="TextBox1" PopupButtonID="Button1" OnClientDateSelectionChanged="checkDate">
    </asp:CalendarExtender>
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
    <asp:Button ID="Button2" runat="server" Text="test"/>
    <asp:CalendarExtender ID="CalendarExtender2" BehaviorID="CalendarExtender2" Format="dd/M/yy" runat="server" TargetControlID="TextBox2" PopupButtonID="Button2">
    </asp:CalendarExtender>
    </form>
</body>
</html>

Try this

<asp:CalendarID="Calendar1"runat="server"OnDayRender="Calendar1_DayRender"></asp:Calendar>

Protected
void
Calendar1_DayRender(object sender,DayRenderEventArgs
e
){
if(e.Day.Date>
DateTime.Today){ e.Day.IsSelectable=
false;}
}

You can follow this link to achieve it:
http://vincexu.blogspot.com/2008/11/how-to-disable-dates-which-are-less.html

Hi

refer this link it’s have a good example that may help you

http://www.aspsnippets.com/Articles/AJAX-CalendarExtender-Disable-Future-Date-Selection.aspx

nice then you have to use Compare Validator Expression with my provide demo

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

<asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="TextBox1"

ErrorMessage="CompareValidator" Operator="GreaterThanEqual" Type="Date"></asp:CompareValidator>



And Try to put this on page_load eventprotected void Page_Load(object sender, EventArgs e)
{

CompareValidator1.ValueToCompare = DateTime.Now.ToShortDateString();

}

[RESOLVED]ValidatorCalloutExtender displays under textbox

I have multiple textboxes on a page with ValidatorCalloutExtender when it displays the popup the pop up sits under another txtbox instead of covering the textbox ,

Do i adjust the z-index or something?

thanks

Glen

 

A simple way to resolve this kind of problem, we should set its z-index .   Just like this,  object.style.zIndex = index.

For more details , here is the
document
.

http://forums.asp.net/t/1078345.aspx/1

 

hi..

You have an option to change the display side .You can display the callout extender below the textbox ..

For more refer the below links..

http://www.dotnetcode.in/2011/12/css-for-ajax-validatorcalloutextender.html

I have changed the z:index in the css file but still no go,
Thanks
I just can't to get it, I have the txtboxes set as 0 zindex any lower and chrome doen'st allow you to click on them
 
<div class="utxtw2pos">
                <asp:Label ID="lblw2" runat="server" Text="Width: "></asp:Label><asp:TextBox ID="wid2"
                    runat="server" BorderColor="#0099FF" BorderStyle="Groove" BorderWidth="2px" Width="50"
                    TabIndex="4" MaxLength="4"></asp:TextBox>
                     <asp:RequiredFieldValidator ID="RFwid2" runat="server" ErrorMessage="*" SetFocusOnError="True"  ControlToValidate="wid2" Display="Dynamic" ></asp:RequiredFieldValidator>
           
                    <asp:RangeValidator ID="RVwid2" runat="server" ErrorMessage="Wrong Width!" MaximumValue="1400" MinimumValue="100" SetFocusOnError="True" Type="Integer" ControlToValidate="wid2" Display="None"></asp:RangeValidator>
             <asp:CompareValidator ID="RCwid2" runat="server" ErrorMessage="Must be less than Length 1" Operator="LessThan" Type="Integer" ControlToCompare="len" ControlToValidate="wid2" Display="None"></asp:CompareValidator>
                          <asp:ValidatorCalloutExtender ID="vcbwid2V" runat="server" CssClass="vcall" TargetControlID="RVwid2">
                          </asp:ValidatorCalloutExtender>
                            <asp:ValidatorCalloutExtender ID="vcbwid2C" runat="server" CssClass="vcall" TargetControlID="RCwid2">
                          </asp:ValidatorCalloutExtender>
  </div>
        .vcall div, .vcall td
{
    border: solid 1px #999999;
    background-color: #ECFFFF;
     z-index: 5000;
}
        .vcall .ajax__validatorcallout_popup_table
        {   z-index: 5000;
            display: none;
            border: none;
            background-color: transparent;
            padding: 0px;
        }
        .vcall .ajax__validatorcallout_popup_table_row
        {
            vertical-align: top;
            height: 100%;
            background-color: transparent;
            padding: 0px;
        }
        .vcall .ajax__validatorcallout_callout_cell
        {
            width: 20px;
            height: 100%;
            text-align: right;
            vertical-align: top;
            border: none;
            background-color: transparent;
            padding: 0px;
        }
        .vcall .ajax__validatorcallout_callout_table
        {
            height: 100%;
            border: none;
            background-color: transparent;
            padding: 0px;
        }
        .vcall .ajax__validatorcallout_callout_table_row
        {
            background-color: transparent;
            padding: 0px;
        }
        .vcall .ajax__validatorcallout_callout_arrow_cell
        {
            padding: 8px 0px 0px 0px;
            text-align: right;
            vertical-align: top;
            font-size: 1px;
            border: none;
            background-color: transparent;
        }
        .vcall .ajax__validatorcallout_callout_arrow_cell .ajax__validatorcallout_innerdiv
        {
            font-size: 1px;
            position: relative;
            left: 1px;
            border-bottom: none;
            border-right: none;
            border-left: none;
            width: 15px;
            background-color: transparent;
            padding: 0px;
        }
        .vcall .ajax__validatorcallout_callout_arrow_cell .ajax__validatorcallout_innerdiv div
        {
            height: 1px;
            overflow: hidden;
            border-top: none;
            border-bottom: none;
            border-right: none;
            padding: 0px;
            margin-left: auto;
        }
        .vcall .ajax__validatorcallout_error_message_cell
        {
            font-family: Verdana;
            font-size: 10px;
            padding: 5px;
            border-right: none;
            border-left: none;
            width: 100%;
        }
        .vcall .ajax__validatorcallout_icon_cell
        {
            width: 20px;
            padding: 5px;
            border-right: none;
        }
        .vcall .ajax__validatorcallout_close_button_cell
        {
            vertical-align: top;
            padding: 0px;
            text-align: right;
            border-left: none;
        }
        .vcall .ajax__validatorcallout_close_button_cell .ajax__validatorcallout_innerdiv
        {
            border: none;
            text-align: center;
            width: 10px;
            padding: 2px;
            cursor: pointer;
        }

Hi,

Please debug with IE Deeloper Tools. Check which css you should be change.

For details, please refer to:

http://msdn.microsoft.com/en-us/library/ie/gg589507(v=vs.85).aspx.

Any more question, please feel free to reply.

This didn’t help and only confused me more,

 

I have sorted it by changing all my z-indexes on my divs

Hi,

Please make sure the callout z-index is higher than texbox.

Any more question, please feel free to reply.

I layed my divs z-indexes so as you headed to the right the lower the z-index got

.ctxtlpos {
	position: absolute;
	z-index: 4;
	left: 239px;
	top: 308px;
}

.ctxtlposro {
	position: absolute;
	z-index: 3;
	left: 273px;
	top: 356px;
}

Databound Dropdown List Does Not Update When Control Parameters Change

I have two databound DropDownLists un an UpdatePanel that do not update when the Control Parameters change: 

<asp:UpdatePanel runat="server" RenderMode="Inline" >
	<Triggers>
		<asp:AsyncPostBackTrigger ControlID="txt_startdate" />
		<asp:AsyncPostBackTrigger ControlID="txt_enddate" />
		<asp:AsyncPostBackTrigger ControlID="ddl_status" />
		<asp:AsyncPostBackTrigger ControlID="ddl_category" />
	</Triggers>
	<ContentTemplate>
		Start Date:&nbsp;
		<asp:TextBox runat="server" id="txt_startdate" columns="10" AutoPostBack="true" Font-Size="10px" />
		<ajaxToolkit:CalendarExtender ID="ajx_startdate" runat="server" TargetControlID="txt_startdate" Format="MM/dd/yyyy" />
		<asp:CompareValidator id="cv_edt_startdate" runat="server" ControlToValidate="txt_startdate" operator="DataTypeCheck" Type="Date" ErrorMessage="Please enter a valid Start Date (mm/dd/yyyy)." EnableClientScript="False" Display="Dynamic" Text="<span <span class='boldred'>*</span>" />&nbsp;&nbsp;
		
		&nbsp;&nbsp;End Date:&nbsp;
		<asp:TextBox runat="server" id="txt_enddate" columns="10" AutoPostBack="true" Font-Size="10px" />
		<ajaxToolkit:CalendarExtender ID="ajx_enddate" runat="server" TargetControlID="txt_enddate" Format="MM/dd/yyyy" />
		<asp:CompareValidator id="cv_edt_enddate" runat="server" ControlToValidate="txt_enddate" operator="DataTypeCheck" Type="Date" ErrorMessage="Please enter a valid End Date (mm/dd/yyyy)." EnableClientScript="False" Display="Dynamic" Text="<span <span class='boldred'>*</span>" />&nbsp;&nbsp;

		&nbsp;&nbsp;Project Status:&nbsp;
		<asp:DropDownList runat="server" ID="ddl_status" AppendDataBoundItems="true" AutoPostBack="true" Font-Size="10px" DataSourceID="SqlDataSource6" DataValueField="id" DataTextField="status" >
			<asp:ListItem Value="%" Text="Select a Status..." />
		</asp:DropDownList>&nbsp;&nbsp;

		&nbsp;&nbsp;Project Category:&nbsp;
		<asp:DropDownList runat="server" ID="ddl_category" AppendDataBoundItems="true" AutoPostBack="true" Font-Size="10px" DataSourceID="SqlDataSource7" DataValueField="id" DataTextField="category" >
			<asp:ListItem Value="%" Text="Select a Category..." />
		</asp:DropDownList>&nbsp;&nbsp;
	</ContentTemplate>
</asp:UpdatePanel>

<asp:SqlDataSource ID="SqlDataSource6" runat="server" ConnectionString="<%$ ConnectionStrings:cs_cfa_r %>" EnableViewState="false" >
	<SelectParameters>
		<asp:ControlParameter ControlID="txt_startdate" type="DateTime" Name="startdate" />
		<asp:ControlParameter ControlID="txt_enddate" type="DateTime" Name="enddate" />
	</SelectParameters>
</asp:SqlDataSource>

<asp:SqlDataSource ID="SqlDataSource7" runat="server" ConnectionString="<%$ ConnectionStrings:cs_cfa_r %>" EnableViewState="false" >
	<SelectParameters>
		<asp:ControlParameter ControlID="txt_startdate" type="DateTime" Name="startdate" />
		<asp:ControlParameter ControlID="txt_enddate" type="DateTime" Name="enddate" />
	</SelectParameters>
</asp:SqlDataSource>

(The Select Commands are set in the Page_Load event). Short of manually rebuilding the DropDownLists on the TextChanged events for the Control Parameters is there a way to fix this?

Call TextChanged event of TExtBoxes and in that event call

ddl_status.DataBind() and  ddl_category.DataBind() methods

Like

<asp:TextBox runat="server" ID="txt_startdate" Columns="10" AutoPostBack="true" Font-Size="10px"
    OnTextChanged="txt_startdate_TextChanged" />

and

protected void txt_startdate_TextChanged(object sender, EventArgs e)
{
    ddl_status.DataBind();
    ddl_category.DataBind();
}

Nasser Malik

Call TextChanged event of TExtBoxes and in that event call

ddl_status.DataBind() and  ddl_category.DataBind() methods

Unfortunately, that does not work  — the contents of the DropDownList is appended to — probably because of the AppendDataBoundItems="true" parameter.

Why is the command set in page_load? Also put a breakpoint in your code to make sure the textbox(es) are in fact causing a postback.

MetalAsp.Net

Why is the command set in page_load? Also put a breakpoint in your code to make sure the textbox(es) are in fact causing a postback.

The postback is most definitely working because there is also a GridView on the page (also tied to the text boxes) and the GridView works fine.

The Command and Connection strings are set in Page_Load because the application determines which database and tables to use at run time. I should add that I did put the Connection String and the Select Command parameters in the Markup — removing them from
the Page_Load event – and I still had the same problem.

[RESOLVED]Validate enter value inside grid

In my gridview have to check enter value for template field is greater than or equal in my data keyname value in my grid view. If its greater than i want to show message (label control). Now i used compare validation control for it . need javascript

Thnks

In  following code, I’ve used data-item attribute to have column value(to be compared) and span for displaying message:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True" DataKeyNames="Items">
        <Columns>
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:TextBox runat="server" ID="txt1" CssClass="txt1" data-item='<%# Eval("Items")%>'>
                    </asp:TextBox>
                    <span style="display:none;color:red">Greater value</span>
                 </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

<script type="text/javascript">
        $('.txt1').blur(function () {
            if (parseInt($(this).val()) > parseInt($(this).data('item'))) {
                $(this).next().show();
                $(this).focus();
                return false;
            }
            else {
                $(this).next().hide();
            }
        })
    </script>


On CS side:

        Person[] persons = {
                               new Person { FirstName="Damon", Items=20 },
new Person { FirstName="Niki", Items=25 },
new Person { FirstName="Ayrton", Items=20 },
new Person { FirstName="Graham", Items=52 }
};

        GridView1.DataSource = persons;
        GridView1.DataBind();

Hope, It helps.

Dear joy.. 

This one isnt work.

Tested again …It’s working fine…

Make sure you are using jquery 1.5 or above…

what error are you getting?

i use vs 3.5 . I didnt get any error or anything. 

Check following rendered html demo:

http://jsfiddle.net/WFHZm/

Hi,

could u post a sample code which can simulate ur problem
with minimal coding? so that anyone can help in that.

Here 1st and 2nd coloumn binding from dataset. and datakey also comming from dataset. i want to compare my enter value in 4th coloumn  with datakey

<script>
function DoSum(textBox) {
var row = textBox.parentNode.parentNode; 
var value3 = parseFloat(row.childNodes[2].childNodes[0].value);
var value4 = parseFloat(row.childNodes[3].childNodes[0].value);
row.childNodes[4].childNodes[0].value = (isNaN(value3) ? 0 : value3) + (isNaN(value4) ? 0 : value4);
}
</script>

<asp:GridView ID="grvReturnNote" runat="server" AllowSorting="True" 
AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC" 
BorderStyle="Solid" BorderWidth="1px" CellPadding="2" CssClass="Gridtablestyle" 
EmptyDataRowStyle-CssClass="Labelstyle" EmptyDataText="No records to display" 
Height="16px" ShowFooter="True" TabIndex="13" Width="903px" 
DataKeyNames="SaleQty" 
onrowdatabound="grvReturnNote_RowDataBound">
<RowStyle ForeColor="#000066" />
<EmptyDataRowStyle BorderStyle="None" BorderWidth="0px" 
HorizontalAlign="Center" />
<Columns>
<asp:BoundField DataField="Description2" HeaderStyle-CssClass="GridPadding" 
HeaderText="Item">
<HeaderStyle CssClass="GridPadding" />
</asp:BoundField>
<asp:TemplateField HeaderText="Total Returns from Sales Rep">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text=’<%# Bind("DamageQty") %>’></asp:TextBox>
</EditItemTemplate>
<ItemTemplate> 
<asp:TextBox ID="txtDmgqty" runat="server" BorderStyle="None" Text=’<%# Bind("DamageQty") %>’></asp:TextBox>
</ItemTemplate>
<ItemStyle HorizontalAlign="Right" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Distributor sendfrom SalesRep">
<ItemTemplate>
<asp:TextBox ID="txtDeliDate" runat="server" Height="21px" 
style="text-align: right" TabIndex="6" 
Width="86px" CssClass="Textboxstyle" 
onchange="DoSum(this)" ValidationGroup="msb"></asp:TextBox>
<asp:CompareValidator ID="CompareValidator1" runat="server" 
ControlToValidate="txtDeliDate" ErrorMessage="*" 
Operator="LessThanEqual" ControlToCompare="txtDmgqty" 
style="text-align: left" Type="Double" ValidationGroup="msb"></asp:CompareValidator>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Distributor Return QTY">
<ItemTemplate>
<asp:TextBox ID="txtDRQTY" runat="server" CssClass="Textboxstyle" Height="21px" 
Width="100px" onchange="DoSum(this)"></asp:TextBox>
<span style="display:none;color:red">Greater value</span>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Total Return QTY">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>

<asp:TextBox ID="txtTotreturns" runat="server" BorderStyle="None" 
ReadOnly="True" Width="100px"></asp:TextBox>
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Distributor Return Reason">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" CssClass="Textboxstyle" 
Width="86px">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
</asp:GridView>

protected void grvReturnNote_RowDataBound(object sender, GridViewRowEventArgs e)
{
try
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (Session["dtReason"] != null)
{
DataTable dtReason = (DataTable)Session["dtReason"];
DropDownList ddlReturns = (DropDownList)e.Row.FindControl("DropDownList1");
ddlReturns.DataSource = dtReason;
ddlReturns.DataTextField = "Description";
ddlReturns.DataValueField = "ReturnType";
ddlReturns.DataBind();
}

}
}

Exactly i need like your demo. 

Here i havent binding to by template . 

ItemTemplate>
                    <asp:TextBox runat="server" ID="txt1" CssClass="txt1" data-item='<%# Eval("Items")%>'>
                    </asp:TextBox>
                    <span style="display:none;color:red">Greater value</span>
                 </ItemTemplate>

so i cant go ahead .
Thanks joy

As per your code:

<asp:TemplateField HeaderText="Distributor Return QTY">
<ItemTemplate>
<asp:TextBox ID="txtDRQTY" runat="server" CssClass="Textboxstyle txt1" Height="21px"  data-item='<%# Eval("SaleQty")%>'
Width="100px" onchange="DoSum(this)"></asp:TextBox>
<span style="display:none;color:red">Greater value</span>
</ItemTemplate>
</asp:TemplateField>

<script type="text/javascript">
        $('.txt1').blur(function () {
            if (parseInt($(this).val()) > parseInt($(this).data('item'))) {
                $(this).next().show();
                $(this).focus();
                return false;
            }
            else {
                $(this).next().hide();
            }
        })
    </script>

Date update problem

I have a ListView doing an update to a table in SQL Server 2008R2.  When I try to remove the date I get the error below (using delete key to remove all numbers.  I am using a masked edit extender to help format the date.  The error does not happen when I
first enter the date and Update, just when I want to clear it.  Any ideas?  Also below is the web page entry and parameter.  The column on the table is a Date data type.  Thanks.

<asp:TextBox ID="txtServiceEnded" runat="server" Text=’<%# Bind("ServiceEnded","{0:d}") %>’ Width="80" Font-Size="12pt" />
<asp:MaskedEditExtender ID="MaskedEditExtender2" runat="server" Mask="99/99/9999"

        TargetControlID="txtServiceEnded" ClearMaskOnLostFocus="True">
</asp:MaskedEditExtender>

<asp:Parameter Name="ServiceEnded" DbType="Date" />

The error is below.

Message: String was not recognized as a valid DateTime.

 

 Stack Trace:

   at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)

   at System.Convert.ToDateTime(String value, IFormatProvider provider)

   at System.String.System.IConvertible.ToDateTime(IFormatProvider provider)

   at System.Convert.ChangeType(Object value, TypeCode typeCode, IFormatProvider provider)

   at System.Web.UI.WebControls.Parameter.GetValue(Object value, String defaultValue, TypeCode type, Boolean convertEmptyStringToNull, Boolean ignoreNullableTypeChanges)

   at System.Web.UI.WebControls.Parameter.GetValue(Object value, String defaultValue, DbType dbType, Boolean convertEmptyStringToNull, Boolean ignoreNullableTypeChanges)

   at System.Web.UI.WebControls.Parameter.GetValue(Object value, Boolean ignoreNullableTypeChanges)

   at System.Web.UI.WebControls.SqlDataSourceView.AddParameters(DbCommand command, ParameterCollection reference, IDictionary parameters, IDictionary exclusionList, String oldValuesParameterFormatString)

   at System.Web.UI.WebControls.SqlDataSourceView.ExecuteUpdate(IDictionary keys, IDictionary values, IDictionary oldValues)

   at System.Web.UI.DataSourceView.Update(IDictionary keys, IDictionary values, IDictionary oldValues, DataSourceViewOperationCallback callback)

   at System.Web.UI.WebControls.ListView.HandleUpdate(ListViewItem item, Int32 itemIndex, Boolean causesValidation)

   at System.Web.UI.WebControls.ListView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup)

   at System.Web.UI.WebControls.ListView.OnBubbleEvent(Object source, EventArgs e)

   at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)

   at System.Web.UI.WebControls.ListViewDataItem.OnBubbleEvent(Object source, EventArgs e)

   at System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args)

   at System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e)

   at System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument)

   at System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)

   at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)

   at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)

   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

Best way to validate MM/dd/yyyy date 

<asp:TextBox ID="txtServiceEnded" runat="server" Width="80" Font-Size="12pt" />
<asp:CompareValidator ID="dateValidator" runat="server" Type="Date" Operator="DataTypeCheck"
    ControlToValidate="txtServiceEnded" ErrorMessage="Please enter a valid date.">
</asp:CompareValidator>

dlchase89

But there is no mask.  User wants a data entry mask like __/__/____ .. Just set ClearMaskOnLostFocus=”false”

You can keep your mask with validator

<asp:TextBox ID="txtServiceEnded" runat="server" Width="80" Font-Size="12pt" />
<asp:CompareValidator ID="dateValidator" runat="server" Type="Date" Operator="DataTypeCheck"
    ControlToValidate="txtServiceEnded" ErrorMessage="Please enter a valid date.">
</asp:CompareValidator>
<asp:MaskedEditExtender ID="MaskedEditExtender2" runat="server" Mask="99/99/9999" 
        TargetControlID="txtServiceEnded" ClearMaskOnLostFocus="True">
</asp:MaskedEditExtender>

Note: Compare validator validate for leap year also.

Regards.

But there is no mask.  User wants a data entry mask like __/__/____