2

I have two DropDownLists populated with Year-Dates, and I want to show an error message in the case where the second ddls value is less than the first ddls value.

This is the code I have used so far, and it doesn't work:

  <asp:CompareValidator 
       ID="cvEndYear2" Operator="GreaterThan" runat="server" CssClass="text-danger" 
       ValidationGroup="Save" ControlToValidate="ddlEndYear" Display="Dynamic" 
       ValueToCompare="ddlStartYear" ErrorMessage="Greater Than" SetFocusOnError="true">
  </asp:CompareValidator>
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
Null
  • 511
  • 5
  • 22

2 Answers2

2

You haven't specified the type, specify the type of data which would be in the textboxes :

 <asp:CompareValidator 
       ..........
       ..........
       ControlToValidate="ddlStartYear" 
       ControlToCompare="ddlEndYear"
       Operator="GreaterThanEqual"
       Type="Integer">
  </asp:CompareValidator>

You might want to have a look at this tutorial

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160
  • [`ValueToCompare`](https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.comparevalidator.valuetocompare(v=vs.110).aspx) compares with a constant value, OP wants to compare with a value of another dropdownlist. – Tim Schmelter Dec 06 '16 at 14:36
2

You have to specify the ControlToCompare and the Operator:

<asp:CompareValidator 
   ID="cvEndYear2" Operator="GreaterThan" runat="server" CssClass="text-danger" 
   ValidationGroup="Save" 
   ControlToValidate="ddlEndYear" Display="Dynamic" 
   ControlToCompare="ddlStartYear"
   Operator="GreaterThanEqual"
   Type="Integer"
   ErrorMessage="The end year must be greater/equal the start year" SetFocusOnError="true">
</asp:CompareValidator>
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • 1
    either use ``ControlToCompare`` or ``ValueToCompare``, not both at same time – Ehsan Sajjad Dec 06 '16 at 14:30
  • 1
    @EhsanSajjad: thanks. However, msdn [mentions](https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.comparevalidator.controltocompare(v=vs.110).aspx) that: "If both properties are set, the ControlToCompare property takes precedence". Since OP wants to compare two controls he has to use `ControlToCompare`. Is that correct? – Tim Schmelter Dec 06 '16 at 14:30
  • @TimSchmelter thanks for clarification, did'nt knew that bit, now will keep in mind that :) – Ehsan Sajjad Dec 06 '16 at 14:38