Click here to Skip to main content
15,890,973 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I have a datagridview in my winform. I have returned 10 rows of records from database and I will display these 10 rows onto the datagridview.
But before I populate the records, I will have some codes to determine the color and font style of the row(s). My codes are as below:
foreach (DataGridViewRow dgvRow in dgvValue.Rows)
{
     if (certain condition)
     {
          dgvRow.DefaultCellStyle.Font = new Font(dgvValue.Font, FontStyle.Italic);
          dgvRow.DefaultCellStyle.BackColor = Color.LightGray;
     }
}


It works as expected. The issue is when I scroll the datagridview, the customized row(s) would revert back to their default style of color and font style.

Any help would be appreciated. Thank you.

What I have tried:

1. Went to check Properties of the datagridview in design view. Saw RowsDefaultCellStyle but still reserve on this option as this is just the overall default style of the rows.
2. Search online for explanation but none article seems to be exact same scenario as mine.
Posted
Updated 1-Jul-21 18:15pm
v2

1 solution

Without seeing your code to load the DB we can't tell - but I'd suspect that's involved somewhere.

The way I'd do it is to put the decision into the DGV CellPainting or RowPrePaint events:
DataGridView.CellPainting Event (System.Windows.Forms) | Microsoft Docs[^]
DataGridView.RowPrePaint Event (System.Windows.Forms) | Microsoft Docs[^]

This may help: Colouring DataGridView Cells According to their Content in WinForms[^]
 
Share this answer
 
Comments
Jamie888 2-Jul-21 2:06am    
Hello @OriginalGriff, thank you for the explanation. I have looked into other articles too and after I have added/modify the codes:
1. dgvRow.ReadOnly = true;
2. Font f = new Font(dgvRow.Cells[1].InheritedStyle.Font.Name, dgvRow.Cells[1].InheritedStyle.Font.Size, FontStyle.Italic);
dgvRow.DefaultCellStyle.Font = f;

It is working. The rows' style did not get overwritten anymore. I am still studying on why these 2 lines would do the tricks.
I would definitely look into your suggestion too. They might be a more complete solution than what I have.

Thank you.
Jamie888 2-Jul-21 2:07am    
.Cells[1] is the column I want to have as the main column for users to concentrate on. Thus .Cells[1] is used.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900