3
Reply

CompareTo not working for DateTime

Dani Oprean

Dani Oprean

Sep 3 2010 9:37 AM
8.4k

Hi,

I have a bit of an odd problem. I have a grid that i must load some data to and sort it by date. I implemented CompareTo but it doesn't seem to work at all.

The objects in the grid seem to be put there at random. I tried to implement compareto in 3 ways. None of them worked. I do  the sorting before i bind to the grid.

The code for the compareto method is this:

public int CompareTo(Issue to)</pre></pre>        {  
  1.             if (this.LastStatusDate.Year > to.LastStatusDate.Year) return 1;  
  2.             else return 0;  
  3.             if ((this.LastStatusDate.Year == to.LastStatusDate.Year) &&  
  4.                 (this.LastStatusDate.Month > to.LastStatusDate.Month)) return 1;  
  5.             else return 0;  
  6.             if ((this.LastStatusDate.Year == to.LastStatusDate.Year) &&  
  7.                 (this.LastStatusDate.Month == to.LastStatusDate.Month) &&  
  8.                 (this.LastStatusDate.Day > to.LastStatusDate.Day)) return 1;  
  9.             else return 0;  
  10.             if ((this.LastStatusDate.Year == to.LastStatusDate.Year) &&  
  11.                 (this.LastStatusDate.Month == to.LastStatusDate.Month) &&  
  12.                 (this.LastStatusDate.Day == to.LastStatusDate.Day) &&  
  13.                 (this.LastStatusDate.Hour > to.LastStatusDate.Hour)) return 1;  
  14.             else return 0;  
  15. }  


The other 2 versions i tried were:


public int CompareTo(Issue to)
{
       if (this.LastStatusDate.CompareTo(to.LastStatusDate)<0) return 1;
       else return 0;
}



public int CompareTo(Issue to) { if (this.LastStatusDate > to.LastStatusDate) return 1; else return 0; }
I also tried DateTime.Compare(date1,date2). This didn't work either.
Any idea why the records in my gridview come up in complete disorder?
Thanks and regards,
Dani

Answers (3)