C# 替换 DataGridView 中的 DateTime.MinValue

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/568483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 08:34:07  来源:igfitidea点击:

Replacing a DateTime.MinValue in a DataGridView

c#datetimesqlitedatagridview

提问by Jared Harley

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.

我正在开发名称记录应用程序,信息存储在 SQLite 数据库中。数据库中的所有列都是 TEXT 类型,但出生日期列除外,它是 DATETIME。我转移到 SQLite 数据库的原始 Access 数据库允许出生日期为空,因此当我复制它时,我将所有空值设置为 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.

我的问题是没有出生日期的行,数据库有 DateTime.MinValue,它在我的 DataGridView 中显示为 01/01/0001。

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

我正在寻找一种方法来用我的 DataGridView 中的空字符串 ("") 替换 01/01/0001。

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!

有人知道如何用空字符串替换 DataGridView 中的 DateTime.MinValue 吗?谢谢!

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.

编辑:使用 DateTime 转换单元格值允许我必须使用 if 语句,但我仍然无法弄清楚用空字符串替换 MinValues 的编码。

采纳答案by Barbaros Alp

You just need to cast it to DateTime

你只需要将它转换为 DateTime

if ((DateTime)(resultsGrid.CurrentRow.Cells["DateOfBirth"].Value) == DateTime.MinValue)
            {
                 // Set cell value to ""
            }

回答by Chris Ballance

if (yourDateOfBirth != null)
{
    Convert.ToDate(yourDateOfBirth) == DateTime.MinValue
}

回答by Jason

you can cast the object as a DateTime object:

您可以将对象转换为 DateTime 对象:

//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

回答by mletterle

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.

或者您可能必须转换为 DateTime,然后与 MinValue 进行比较,但听起来您的想法是正确的。

回答by Cerebrus

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 incorrectdata and you are trying to post-process the data for display.

虽然实现您需要的转换可能非常简单(请参阅我前面的优秀答案),但我认为您最好将数据库中此特定列中的所有 DateTime.MinValue 值替换为NULL. 这将正确地表示该职位实际缺乏数据。目前您的数据库包含不正确的数据,您正在尝试对数据进行后处理以进行显示。

Consequently, you would be able to handle the display of data in your GridView using the EmptyDataTextor NullDisplayTextproperties to provide appropriate rendering.

因此,您将能够使用EmptyDataTextNullDisplayText属性来处理 GridView 中的数据显示,以提供适当的呈现。

回答by polyglot

There are already answers that should achieve what you want; but I wonder why you don't put NULL in the database to start with? In sqlite3, "datetime" is more or less just a string, (there is nothing special about a datetime column since sqlite3 is all about just type afinity, not type binding), so you just insert NULL in that column. And in case you want to have the MinValue of datetime when you query, you can easily execute a query like

已经有答案可以实现您想要的;但我想知道你为什么不把 NULL 放在数据库中?在 sqlite3 中,“datetime”或多或少只是一个字符串,(日期时间列没有什么特别之处,因为 sqlite3 只是类型关联,而不是类型绑定),因此您只需在该列中插入 NULL。如果您想在查询时获得日期时间的 MinValue,您可以轻松地执行如下查询

select coalesce(your_datetime_column,'01/01/0001') from your_table

回答by Jared Harley

I discovered why the DateTime.MinValuewas displaying!

我发现了为什么DateTime.MinValue显示!

This line in the cell formatting section caused the MinValue of "01/01/0001" to display:

单元格格式部分中的这一行导致“01/01/0001”的 MinValue 显示:

dateOfBirth.DefaultCellStyle.Format = "MM/dd/yyyy";

Without this line, the Date of Birth field in my datagridviewis left blank.

如果没有这一行,我的出生日期字段将datagridview留空。

Barbaros Alp is still correct about what I was trying to do at the time. Thanks everyone!

Barbaros Alp 关于我当时尝试做的事情仍然是正确的。谢谢大家!

回答by Pavel Krejci

Use nullabe DateTime format instead of DateTime ("DateTime?") - don't use string.

使用 nullabe DateTime 格式而不是 DateTime ("DateTime?") - 不要使用字符串。

example:

例子:

public DateTime? mydate;

and then:

进而:

DGview.Rows.Add(mydate.HasValue ? mydate : null);