Bold Cell based on value in data grid

dv2020

Active member
Joined
Dec 18, 2020
Messages
30
Programming Experience
1-3
Hi All,

I have this code below which works well. I'm trying to modify the code so it only bolds the value, and not change the font to "Arial" or the size.

Bold Cell in Data Grid:
    if (cellVal > 0 && e.ColumnIndex > 15 && e.ColumnIndex < 27)
                        { row.Cells[e.ColumnIndex].Style.BackColor = cellpositive;
                         row.Cells[e.ColumnIndex].Style.Font = new Font("Arial", 8.5F, FontStyle.Bold, GraphicsUnit.Pixel);

                    }

I'm having trouble working out how to do this, as the Font Class required a name, and current size, therefore if i remove "Aria'", 8.5 it is not valid.

Any help would be much appreciated

Kind Regards

David
 
Solution
There is a Font constructor that allows you to create a new Font based on an existing one and set the style as you want. You can use the style of the existing Font as a basis too. This will do what you want:
C#:
var currentFont = row.Cells[e.ColumnIndex].Style.Font;

row.Cells[e.ColumnIndex].Style.Font = new Font(currentFont, currentFont.Style | FontStyle.Bold);
That bitwise OR operator(|) is how you combine enumerated flags. If you want to remove a flag then you use currentFont.Style & !FontStyle.Bold and if you want to toggle a flag you use currentFont.Style ^ FontStyle.Bold
Create the new Font based on the existing one, for example use the (Font, FontStyle) constructor.
 
There is a Font constructor that allows you to create a new Font based on an existing one and set the style as you want. You can use the style of the existing Font as a basis too. This will do what you want:
C#:
var currentFont = row.Cells[e.ColumnIndex].Style.Font;

row.Cells[e.ColumnIndex].Style.Font = new Font(currentFont, currentFont.Style | FontStyle.Bold);
That bitwise OR operator(|) is how you combine enumerated flags. If you want to remove a flag then you use currentFont.Style & !FontStyle.Bold and if you want to toggle a flag you use currentFont.Style ^ FontStyle.Bold
 
Solution
There is a Font constructor that allows you to create a new Font based on an existing one and set the style as you want. You can use the style of the existing Font as a basis too. This will do what you want:
C#:
var currentFont = row.Cells[e.ColumnIndex].Style.Font;

row.Cells[e.ColumnIndex].Style.Font = new Font(currentFont, currentFont.Style | FontStyle.Bold);
That bitwise OR operator(|) is how you combine enumerated flags. If you want to remove a flag then you use currentFont.Style & !FontStyle.Bold and if you want to toggle a flag you use currentFont.Style ^ FontStyle.Bold
Thank you, that makes sense and worked perfectly.

Cheers

David
 
Back
Top Bottom