简体   繁体   中英

How can i get values from 2 dropdown lists and compare them as a date in C#

I have 2 dropdown lists that show months and year. I can validate it and check if its less than a certain date in JS but now i wanna do this server side but i cannot figure out how to do pass the selected values and convert them to a date function.

UPDATE:

This is my HTML/ASP.Net

 <asp:CustomValidator ID="CustomValidatorED" runat="server" 
 ErrorMessage=" *Enter a valid Expiry Date" Display="Dynamic" CssClass="error"
 ClientValidationFunction="ValidateED" 
 OnServerValidate="CustomValidatorED_ServerValidate"></asp:CustomValidator>

This is my Code Behind which is incomplete C#:-

protected void CustomValidatorED_ServerValidate(object source, ServerValidateEventArgs args)
{
    var x = EDY.SelectedValue;
      var y = EDM.SelectedValue;

      var z = x + y;
     var pppp = Convert.ToInt32(z);
     DateTime entereddate = new DateTime(pppp);

      DateTime d = DateTime.Now;
      var r = d.Month;
      var p = d.Year;

      var kkkk = r + p;

      DateTime todaysdate = new DateTime(kkkk);

      int result = DateTime.Compare(entereddate, todaysdate);

      if (result < 0)
      { args.IsValid = true; }
      else
      { args.IsValid = false; }

}

`EDY = Years Drop Down`
`EDM = Months Drop Down`

I know i have made some obvious mistakes but this function is being called even when the date is correct, so if the entered date is less than todays date, it should show error but not the other times.

Mainly just want to fix my codebehind to get it working properly as im comparing entered MM/YYYY and todays MM/YYYY

DateTime dtime1 = new DateTime(Convert.ToInt32(ddl1.SelectedValue));
DateTime dtime2 = new DateTime(Convert.ToInt32(ddl2.SelectedValue));

if(dtime1.equals(dtime2))
   doSomething();
//Conversion to comparing Date

DateTime date1 = dtime1.Date;
DateTime date2 = dtime2.Date;

The code above does exactly as you are wondering. Allows you to compare two values from your drop down lists and compare them as DateTimes.

Something like this. You may have to be concerned about how you are converting the date (ie using a format speficiation) if you see that your date comparison is not working in respect to time etc.

protected void CustomValidatorED_ServerValidate(object source, ServerValidateEventArgs args)
    {
        DateTime currentDate = DateTime.Now;

        DateTime chosenDate = Convert.ToDateTime(args.Value);

        if (currentDate <= chosenDate)
        { args.IsValid = true; }
        else
        { args.IsValid = false;}

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM