更改DataGridView中的列中的字体大小

Joh*_*wan 3 c# winforms

我在DataGridView(WinForm应用程序)中有一个列需要更改字体大小和样式.从这里的文章:http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.font.aspx,我认为下面的代码将得到我想要的结果(我是首先通过更改样式进行测试):

this.dataGridViewMain.Columns[3].DefaultCellStyle.Font = new Font(dataGridViewMain.DefaultCellStyle.Font, FontStyle.Italic);
Run Code Online (Sandbox Code Playgroud)

但代码不会改变任何东西.我还试图在RowPostPaint事件处理程序上添加代码,但仍然无法正常工作.我知道程序使用的字体是在DataGridView.RowsDefaultCellStyle属性上设置的,但我认为在RowPostPaint事件中放置代码会覆盖它.以下是活动的代码RowPostPaint:

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
}
Run Code Online (Sandbox Code Playgroud)

任何帮助表示赞赏.谢谢.

Joh*_*wan 7

好的,这就是我发现的.在InitializeComponent()有这一行:

dataGridViewCellStyle3.Font = new System.Drawing.Font("Verdana", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
Run Code Online (Sandbox Code Playgroud)

当我对该行进行注释时,那么代码将斜体显示为RowPostPaint正常的列.然后我在下面添加了代码,RowPostPaint以便其他列字体是粗体并且具有更小的尺寸.我仍然不太确定为什么DataGridView.Columns[colNumber].DefaultCellStyle.Font不覆盖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);
 }
Run Code Online (Sandbox Code Playgroud)


Lai*_*zor 4

字体大小是只读的,因此您需要制作新字体并设置 yourDataGridView.Font = new Font(name,size,style) 这里有更多信息:http ://msdn.microsoft.com/en-us/library/系统绘图字体.aspx