I’m trying to sort by date with linq when I already have a date brought back from linq that I converted to a shortdatestring:
var NOVs = from n in db.CT_NOVs
join i in db.CT_Inspectors on n.ARBInspectorID equals i.CTInspectorID
join v in db.CT_ViolationTypes on n.ViolationTypeID equals v.ViolationTypeID
join t in db.CT_Tanks on n.CargoTankID equals t.CargoTankID
join c in db.CT_Companies on t.CompanyID equals c.CompanyID
select new
{
n.NOVID,
n.NOVNumber,
NOVDate = n.NOVDate.Value.ToShortDateString(),
ARBInspectorFirstName = i.FirstName,
ARBInspectorLastName = i.LastName,
v.ViolationName,
t.CargoTankID,
c.CompanyName
};
Here is where I try to sort by the date, but it’s giving me an error since I converted the datetime into a shortdatestring:
if (column == "NOVDate")
{
if (sortDirection == "ascending")
NOVs = NOVs.OrderBy(b => Convert.ToDateTime(b.NOVDate));
else
NOVs = NOVs.OrderByDescending(b => Convert.ToDateTime(b.NOVDate));
}
Any clue on how to sort by NOVDate?
Why don’t you leave it as a full DateTime object and convert it to a ShortDateString right before you display it to the user? I usually try to leave the objects in their native format and convert them to display to the user at the last second. That’ll help with separating your data layer from your presentation layer too, i.e., let the presentation layer decide how to display the date to the user; your data layer shouldn’t really care.
From the comments:
Since you’re using a
<asp:BoundField>element with your GridView, you can use the DataFormatString property to have the grid view automatically format it.It looks like using
DataFormatString="{0:d}"should do the trick. (thanks Gromer!)