locked
Compare today's date to a column and highlight the cell RRS feed

  • Question

  • In my winform app , there is a column called "Next_Calibration_On"(in the format "dd-MM-yyyy") with which i have to compare today date if it is less than it then i want highlight the cell in the datagrid view in red . Fr this i have the below code :

     private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
            {
                DateTime currentToday = (DateTime)this.dataGridView1.Rows[e.RowIndex].Cells["Next_Calibration_On"].Value;
    
                if (currentToday <= DateTime.Now.Date)
                {
                    e.CellStyle.ForeColor = Color.Red; //Font Color
                    e.CellStyle.SelectionForeColor = Color.Red; //Selection Font color
                }

    However this is showing the error message as below:

    System.ArgumentException: 'Column named Next_Calibration_On cannot be found.Parameter name: columnName'
    But i do have column in my table ..how to solve this?


    Tuesday, July 28, 2020 3:43 AM

Answers

  • Hi

    @Karen provide a good solution .After that you can use CellPainting event for  formating

      private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
            {
                try
                {
                    var cellvalue = dataGridView1.Rows[e.RowIndex].Cells["Next_Calibration_On"].Value;
                    if(Convert.ToDateTime(cellvalue) < DateTime.Now)
                    dataGridView1.Rows[e.RowIndex].Cells["DateTimeCol"].Style.ForeColor = Color.Red;
                    dataGridView1.Rows[e.RowIndex].Cells["DateTimeCol"].Style.SelectionForeColor = Color.Red;
                }
                catch (Exception)
                {
    
                  //  throw;
                }
               
            }

    Thanks and regards

    Tuesday, July 28, 2020 4:19 PM

All replies

  • Investigate the dataGridView1.Columns collection (in Watch window, for example) and confirm that it contains the column.

    If this column is not displayed in the grid and you are using Data Binding, then consider dataGridView1.Rows[e.RowIndex].DataBoundItem, which is probably a DataRow object that contains all of values.

    Tuesday, July 28, 2020 5:23 AM
  • Hi Ravi Kumar12233,

    Thank you for posting here.

    Although the column names we see in Data Sources and the column names displayed in Datagridview are Next_Calibration_On, in fact, the column name of this column is nextCalibrationOnDataGridViewTextBoxColumn.

    When using the Data source as a data source, it will remove the underscore in the column name, then add the column type at the end to form the final column name.

    You can modify it in the position shown in the figure, or use index instead of column name to access it.

    Update:

    This line will cause an error: System.NullReferenceException:'Object reference not set to an instance of an object.'

    DateTime currentToday = (DateTime)this.dataGridView1.Rows[e.RowIndex].Cells["Next_Calibration_On"].Value;


    The reason is that datagridview has a blank row at the bottom by default,

    When this line of code attempts to cast a null value to datetime, this error will occur.

    You can use Convert.ToDateTime() to replace it, or set the AllowUserToAddRows property of the datagridview to false to remove this line.

    Hope this could be helpful.

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, July 28, 2020 7:31 AM
  • Hello,

    The following focus is on a property named HireDate where the DataGridViewColumn name is HireDateColumn.

    public partial class EmployeeForm : Form
    {
        public EmployeeForm()
        {
            InitializeComponent();
    
            employeeDataGridView.AutoGenerateColumns = false;
    
            Shown += EmployeeForm_Shown;
    
            employeeDataGridView.CellFormatting += EmployeeDataGridView_CellFormatting;
        }
    
        private void EmployeeDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (employeeDataGridView.Rows[e.RowIndex].IsNewRow != false ||
                e.ColumnIndex != employeeDataGridView.Columns["HireDateColumn"].Index) return;
    
            var currentToday = (DateTime)employeeDataGridView.Rows[e.RowIndex].Cells["HireDateColumn"].Value;
            if (currentToday.Year > 1993)
            {
                e.CellStyle.ForeColor = Color.Red; //Font Color
                e.CellStyle.SelectionForeColor = Color.Red; //Selection Font color                    
            }
        }
      private void EmployeeForm_Shown(object sender, EventArgs e)
        {
            using (var context = new NorthwindContext())
            {
                employeeDataGridView.DataSource = context.Employees
                    .Select(emp => new
                    {
                        id = emp.EmployeeID,
                        FirstName = emp.FirstName,
                        LastName = emp.LastName,
                        HireDate = emp.HireDate.Value // HireDateColumn
                    }).ToList();
            }
        }
    }


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    • Proposed as answer by Naomi N Tuesday, July 28, 2020 1:49 PM
    Tuesday, July 28, 2020 1:44 PM
  • Hi

    @Karen provide a good solution .After that you can use CellPainting event for  formating

      private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
            {
                try
                {
                    var cellvalue = dataGridView1.Rows[e.RowIndex].Cells["Next_Calibration_On"].Value;
                    if(Convert.ToDateTime(cellvalue) < DateTime.Now)
                    dataGridView1.Rows[e.RowIndex].Cells["DateTimeCol"].Style.ForeColor = Color.Red;
                    dataGridView1.Rows[e.RowIndex].Cells["DateTimeCol"].Style.SelectionForeColor = Color.Red;
                }
                catch (Exception)
                {
    
                  //  throw;
                }
               
            }

    Thanks and regards

    Tuesday, July 28, 2020 4:19 PM
  • THank you so much for all your great suggestions ..it solved now
    Thursday, July 30, 2020 10:40 AM