Replacing a DateTime.MinValue in a DataGridView

后端 未结 8 1608
悲哀的现实
悲哀的现实 2021-01-17 22:42

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

相关标签:
8条回答
  • 2021-01-17 23:23

    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.

    0 讨论(0)
  • 2021-01-17 23:28

    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);
    
    0 讨论(0)
  • 2021-01-17 23:30

    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
    
    0 讨论(0)
  • 2021-01-17 23:30
    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.

    0 讨论(0)
  • 2021-01-17 23:39

    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!

    0 讨论(0)
  • 2021-01-17 23:40

    You just need to cast it to DateTime

    if ((DateTime)(resultsGrid.CurrentRow.Cells["DateOfBirth"].Value) == DateTime.MinValue)
                {
                     // Set cell value to ""
                }
    
    0 讨论(0)
提交回复
热议问题