I have a column in a DataGridView (WinForm application) that needs the font size and style changed. From the article here: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.font.aspx , I am thinking that the code below will get the result that I want (I am testing by changing the styling first):
this.dataGridViewMain.Columns[3].DefaultCellStyle.Font = new Font(dataGridViewMain.DefaultCellStyle.Font, FontStyle.Italic);
But the code does not change anything. I also tried to add the code on the RowPostPaint
event handler but still does not work. I know the font that is used by the program is set on the DataGridView.RowsDefaultCellStyle
properties but I thought placing code in the RowPostPaint
event will override that. Below is the code from the RowPostPaint
event:
void dataGridViewMain_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
this.dataGridViewMain.Columns[3].DefaultCellStyle.BackColor = Color.Gray;
foreach (DataGridViewRow row in this.dataGridViewMain.Rows)
{
int daysInShop = Convert.ToInt32(row.Cells["Days in the shop"].Value);
if (daysInShop > 4)
{
row.DefaultCellStyle.BackColor = Color.Red;
row.DefaultCellStyle.ForeColor = Color.White;
}
else if (daysInShop > 2)
{
row.DefaultCellStyle.BackColor = Color.Yellow;
}
else
{
row.DefaultCellStyle.BackColor = Color.YellowGreen;
}
row.Height = 35;
}
this.dataGridViewMain.CurrentCell = null; // no row is selected when DGV is displayed
}
Any help is appreciated. Thanks.
Ok this is what I found out. Under InitializeComponent()
there is this line:
dataGridViewCellStyle3.Font = new System.Drawing.Font("Verdana", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
When I comment that line out, then the code to italicize a column that is in RowPostPaint
works fine. I then added the code below in the RowPostPaint
so that other columns font are bold and have smaller size. I am still not quite sure why DataGridView.Columns[colNumber].DefaultCellStyle.Font
does not override dataGridViewCellStyle3
int colCount = dataGridViewMain.ColumnCount;
for (int i = 0; i < colCount; i++)
{
if(i != 3)
this.dataGridViewMain.Columns[i].DefaultCellStyle.Font = new System.Drawing.Font("Verdana", 14F, FontStyle.Bold);
else
this.dataGridViewMain.Columns[3].DefaultCellStyle.Font = new System.Drawing.Font("Verdana", 25F, FontStyle.Bold);
}
Font size is read only so you would want to make a new font and set yourDataGridView.Font = new Font(name,size,style) here is more info: http://msdn.microsoft.com/en-us/library/system.drawing.font.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With