I am working on a name record application and the information is stored in a SQLite database. All columns in the database are TEXT types, except for the date of birth column
While it may be quite straightforward to achieve the transformation you need (see the excellent answers preceding mine), I feel that you should ideally replace all the DateTime.MinValue values in this particular column in the database with NULL
. This would correctly represent the actual lack of data in this position. At present your database contains incorrect data and you are trying to post-process the data for display.
Consequently, you would be able to handle the display of data in your GridView using the EmptyDataText
or NullDisplayText
properties to provide appropriate rendering.
Use nullabe DateTime format instead of DateTime ("DateTime?") - don't use string.
example:
public DateTime? mydate;
and then:
DGview.Rows.Add(mydate.HasValue ? mydate : null);
you can cast the object as a DateTime object:
//create a nullable intermediate variable
System.DateTime? dtCellValue = resultsGrid.CurrentRow.Cells["DateOfBirth"].Value as System.DateTime?;
//if this cell has been set to String.Emtpy the cast will fail
//so ensure the intermediate variable isn't null
if ( dtCellValue.HasValue && dtCellValue == System.DateTime.MinValue )
//set cell value appropriately
private void resultsGrid_DateFormatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
{
if(resultsGrid.Columns[e.ColumnIndex].Name.Equals("DateOfBirth"))
{
if ((string)resultsGrid.CurrentRow.Cells["DateOfBirth"].Value == DateTime.MinValue.ToString())
{
// Set cell value to ""
}
}
}
Or you might have to cast to DateTime and then compare to MinValue, but it sounds like you have the right idea.
I discovered why the DateTime.MinValue
was displaying!
This line in the cell formatting section caused the MinValue of "01/01/0001" to display:
dateOfBirth.DefaultCellStyle.Format = "MM/dd/yyyy";
Without this line, the Date of Birth field in my datagridview
is left blank.
Barbaros Alp is still correct about what I was trying to do at the time. Thanks everyone!
You just need to cast it to DateTime
if ((DateTime)(resultsGrid.CurrentRow.Cells["DateOfBirth"].Value) == DateTime.MinValue)
{
// Set cell value to ""
}