Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing a DateTime.MinValue in a DataGridView

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, which is a DATETIME. The original Access database that I transferred to the SQLite database allowed nulls for the date of birth, so when I copied it over, I set all nulls to DateTime.MinValue.

In my application, the date of birth column is formatted like so:

DataGridViewTextBoxColumn dateOfBirth = new DataGridViewTextBoxColumn();
        dateOfBirth.HeaderText = "DOB";
        dateOfBirth.DataPropertyName = "DateOfBirth";
        dateOfBirth.Width = 75;
        dateOfBirth.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
        dateOfBirth.DefaultCellStyle.Format = "MM/dd/yyyy";

My problem is that rows where there is not a date of birth, the database has DateTime.MinValue, which displays in my DataGridView as 01/01/0001.

I am looking for a way to replace the 01/01/0001 with an empty string ("") in my DataGridView.

private void resultsGrid_DateFormatting(object sender, System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
    {
        if(resultsGrid.Columns[e.ColumnIndex].Name.Equals("DateOfBirth"))
        {
            if ((DateTime)(resultsGrid.CurrentRow.Cells["DateOfBirth"].Value) == DateTime.MinValue)
            {
                 // Set cell value to ""
            }
        }
    }

Anyone have an idea how I can replace a DateTime.MinValue in my DataGridView with an empty string? Thanks!

Edit: Casting the cell value with DateTime allows the if statement I have to work, but I am still not able to figure out the coding to replace the MinValues with a blank string.

like image 211
Jared Harley Avatar asked Feb 20 '09 06:02

Jared Harley


2 Answers

You just need to cast it to DateTime

if ((DateTime)(resultsGrid.CurrentRow.Cells["DateOfBirth"].Value) == DateTime.MinValue)
            {
                 // Set cell value to ""
            }
like image 158
Barbaros Alp Avatar answered Oct 10 '22 05:10

Barbaros Alp


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!

like image 29
Jared Harley Avatar answered Oct 10 '22 06:10

Jared Harley