Thursday, March 18, 2010

C# Handling Dates in a Datagrid

Here's the code:

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//See if its empty first
if (Convert.ToString(DataBinder.Eval(e.Row.DataItem, "DateField") + "") == "")
{
//if empty do nothing
}
else
{
DateTime dDate = Convert.ToDateTime(DataBinder.Eval(e.Row.DataItem, "DateField"));
((TextBox)e.Row.FindControl("tbxDateField")).Text = da.FixDate(dDate);
}
}
}

Inside the da:
//this strips the time off of the date
public string FixDate(DateTime cDate)
{
string fDate = Convert.ToString(cDate);
string NewDate = fDate.Substring(0, fDate.LastIndexOf("/") + 5);
// look for 1/1/1900 because sql puts this into empty datefields
if (NewDate == "1/1/1900")
{
NewDate = "";
return NewDate;
}
else
{
return NewDate;
}
}

No comments: