There is software for highlighting when the date has expired, the problem is that when you run the software, the lines in the dataGridView are visually floating. How to fix?

The code below, if you remove it, the lines are displayed correctly.

private void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e) { if (e.RowIndex < 0 || dataGridView1.Rows[e.RowIndex].IsNewRow) return; var dt = DateTime.Now; dt = new DateTime(dt.Year, dt.Month, dt.Day, 0, 0, 0); if (((DateTime)dataGridView1.Rows[e.RowIndex].Cells["Срок до"].Value).CompareTo(dt) < 0) dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red; 

enter image description here

enter image description here

It is white, but if you scroll the mouse wheel, it paints a second on red in red and immediately becomes white again.

  • And you can add a screenshot? It is difficult to understand what it is about. - Monk
  • added screenshot - Pavel
  • the only thing that found such an exception is the exception "System.InvalidCastException" in ("The specified cast is invalid.") - Paul
  • check the field type: dataGridView1.Rows[e.RowIndex].Cells["Срок до"].Value seems to be a string - Grundy
  • I didn’t find everything I could find why he behaves this way (( - Paul

3 answers 3

Perhaps your option somewhere causes conflict. Try painting through e.Graphics.

 Rectangle rowBounds = new Rectangle( this.dataGridView1.RowHeadersWidth, e.RowBounds.Top, this.dataGridView1.Columns.GetColumnsWidth( DataGridViewElementStates.Visible) - this.dataGridView1.HorizontalScrollingOffset + 1, e.RowBounds.Height); e.Graphics.FillRectangle(new SolidBrush(Color.Red), rowBounds); 

Notice that the text is cut just as far as the incomplete cell sticks out from below. This cell is not completely filled (because it is not fully displayed). In the code proposed by me, a rectangle is formed from the visible part of the line and it is already painted in the desired color. Something like this )

  • interesting solution) I just can’t understand how to associate it with DateTime (((( - Paul
  • @Pavel Yes, also in the condition. I just suggested the coloring method - iRumba
  • Interestingly, he paints over when I twist the wheel of the mouse, and it remains white ( - Paul
  • @ Paul did not understand. I do not have the opportunity to test it. Can you send the screen or explain in more detail? ) - iRumba
  • added the screen what happened - Paul

Maybe try to attach to the event cellpainting?

  private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { if (e.ColumnIndex == 4) { if ((e.Value as DateTime?).Value.CompareTo(DateTime.Now) < 0) (sender as DataGridView).Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red; } } 
  • also also ((((( - Paul

In general, I found the problem, or rather prompted many thanks to this person.

The problem was that in the "Срок до" column there were empty lines because of this, it did not show empty cells.