簡體   English   中英

如何將 dataGrid 日期值與當前日期進行比較?

[英]How to compare dataGrid date value to current date?

我有一個來自 MySQL 的名為Review Date的專欄。 格式化為dd/mm/yyyy

我只是在 dataGridView 上顯示它。

在此處輸入圖像描述

我正在嘗試創建一個語句來將今天的日期與 dataGrid 值進行比較。

這是我嘗試過的:

    private void data_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        DateTime today = DateTime.Today;
        string todayDate = today.ToString("d/M/yyyy");


        foreach (DataGridViewRow Myrow in data.Rows)
        {
            // Cell 6 is the review_date
            if (Myrow.Cells[6].Value.ToString() < todayDate)
            {
                Myrow.DefaultCellStyle.BackColor = Color.Red;
            }
            else
            {
                Myrow.DefaultCellStyle.BackColor = Color.Green;
            }
        }
    }

但我收到一個錯誤:

運算符“<”不能應用於“字符串”和“字符串”類型的操作數

您應該使用Date對象。

DateTime today = DateTime.Now;

foreach (DataGridViewRow Myrow in data.Rows)
{
    DateTime dt = DateTime.Parse(Myrow.Cells[6].Value.ToString());

    if (dt > today)
    {
        Myrow.DefaultCellStyle.BackColor = Color.Red;
    }
    else
    {
        Myrow.DefaultCellStyle.BackColor = Color.Green;
    }
}

另外,快速提示。

如果您想在日期中添加天數或月數。 嘗試這個...

//Add days
if (dt > today.AddDays(10))

//Add months
if (dt > today.AddMonths(12))

您不能對這樣的字符串執行小於運算符。 您需要對日期對象進行比較。 可能是這樣的。

private void data_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    DateTime today = DateTime.Today.Date; //Used .Date to cut off time too

    foreach (DataGridViewRow Myrow in data.Rows)
    {
        var GridDate = DateTime.Today.Date;
        DateTime.TryParse(Myrow.Cells[6], out GridDate); //parse string date

        //Cell 6 is the review_date
        if (GridDate < todayDate)
        {
            Myrow.DefaultCellStyle.BackColor = Color.Red;
        }
        else
        {
            Myrow.DefaultCellStyle.BackColor = Color.Green;
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM