Tuesday, 24 February 2015

How to change the text box date to dd/mm/yyyy format using c#


I want date in a dd/mm/yyyy format with validation in TextBox .

As I got date with dd/mm/yyyy but it will also accept 32/02/2005. Though Feb has less 30 days.


Also when I compare two textbox it will not evalute properly. eg I want TextBox2 date greater then TextBox1. So I had used
CompareValidator, & select type="date" but it will not evalute.


  1.  // .cs code.....
  2. private void DateSubmit_Click(object sender, System.EventArgs e)
  3. {
  4. DateTime date1, date2;
  5. bool date1OK, date2OK;
  6. date1 = new DateTime(1,1,1);
  7. date2 = new DateTime(1,1,1);
  8. try
  9. {
  10. date1 = Convert.ToDateTime(Date1.Text);
  11. date1OK=true;
  12. }
  13. catch
  14. {
  15. date1OK = false;
  16. }
  17. try
  18. {
  19. date2 = Convert.ToDateTime(Date2.Text);
  20. date2OK=true;
  21. }
  22. catch
  23. {
  24. date2OK = false;
  25. }
  26. if(date1OK && date2OK)
  27. {
  28. if(date1.CompareTo(date2) > -1)
  29. lblResult.Text = "Date2 must be after Date1";
  30. else
  31. {
  32. //do whatever here
  33. }
  34. }
  35. else lblResult.Text = "Invalid date format. Please check your input in the Date1 and Date2 fields";
  36. }

2 comments:

  1. Really nice blog post.provided a helpful information.I hope that you will post more updates like this Ruby on Rails Online Course India


    ReplyDelete