Changing DataGridViewRow font style in C#

Published January 20th, 2008

Just a quick note-to-self to remind me of the (rather over-complex, if you ask me) means by which you alter the basic font style properties of a DatagridViewRow element. It involves the DataGridViewRow.DefaultCellStyle.Font property, but all the basic properties — FontFamily, Size and Style — are write-only.

In order to change them, you have to overwrite the entire Font property by creating a new Font object and specifying its properties when you instantiate it. So for example:

DataGridViewRow row = new DataGridViewRow();
row.DefaultCellStyle.Font = new Font (
“Arial”, // Family
9, // Size
FontStyle.Bold // Style
);

..but what if you just want to alter one of these properties, and preserve whatever is already set for the others?

Well if you’re creating a new row, you can’t reference the properties of the row itself (because it doesn’t exist yet) but you can refer to the corresponding settings for the row’s parent DataGridView. So lets say we just want to change the row to bold:

DataGridView data_grid = new DataGridView();
DataGridViewRow row = new DataGridViewRow();
row.DefaultCellStyle.Font = new Font(
data_grid.DefaultCellStyle.Font.FontFamily,
data_grid.DefaultCellStyle.Font.Size,
FontStyle.Bold
);

So the default settings for font family and size are preserved, but the bold setting is changed.

Get a Trackback link

1 Comments

  1. C_moua on August 5, 2009

    Thanks man :)

Leave a comment

Comment Policy: First time comments are moderated. Please be patient.

OpenID

Anonymous