简体   繁体   中英

Dynamically cell color change in DataGridView

I am working on a database application. In which some columns are text column and one column is for date. I want to compare Column's date with system date and want to turn cell background color Red when column's date value is less than system date. Below given codes I have tried but not working.

private void EMIDGVAdm_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        if (this.EMIDGVAdm.Columns[e.ColumnIndex].DataPropertyName == "Date_1")
        {
            var EMIDate = Convert.ToDateTime(EMIDGVAdm.Rows[e.RowIndex].Cells["Date_1"].Value);
            if (EMIDate <= DateTime.Now)
            {
                e.CellStyle.BackColor = Color.Red;
                //e.CellStyle.ForeColor = Color.Red;
            }
        }
    }

Use Today if time part is not needed. A try catch handles possible null in date field. Have to use gridview columns collection name in the var EMIDate line which is probably different from the DataPropertyName. So for the gridview in your working procedure, they are likely the same.

Analyzed OP's project. Seems the code would not read columns out of view so had to widen the DataGridView and panel to display Date_1 column without scrolling. Also, the DataPropertyName does not have underscore. Adjusted design and code works:

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (this.dataGridView1.Columns[e.ColumnIndex].DataPropertyName == "Date 1")
        try
        {
            var EMIDate = Convert.ToDateTime(dataGridView1.Rows[e.RowIndex].Cells["date1DataGridViewTextBoxColumn"].Value);
            if (EMIDate <= DateTime.Today)
            {
                e.CellStyle.BackColor = Color.Red;
            }
        }
        catch
        {
        }
}

Found a textbox that appears to be misnamed. Possibly textBox6 should be txtEMI6 for consistency with naming of other controls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM