更改DataGridView标题单元格的文本对齐和字体大小 [英] Changing DataGridView Header Cells' Text Alignment And The Font Size

查看:174
本文介绍了更改DataGridView标题单元格的文本对齐和字体大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试更改DataGridView的文本对齐方式和字体大小。所有列都是在运行时以编程方式创建的。这是代码..

I'm trying to change the text alignment and the font size of a DataGridView. All the Columns are created programatically at runtime. Here's the code..

private void LoadData()
{
    dgvBreakDowns.ColumnCount = 5;
    dgvBreakDowns.Columns[0].Name = "Breakdown No";
    dgvBreakDowns.Columns[1].Name = "Breakdown Type";
    dgvBreakDowns.Columns[2].Name = "Machine Type";
    dgvBreakDowns.Columns[3].Name = "Date";
    dgvBreakDowns.Columns[4].Name = "Completed";

    dgvBreakDowns.Columns[4].Visible = false;

    foreach (DataGridViewHeaderCell header in dgvBreakDowns.Rows)
    {
        header.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
        header.Style.Font = new Font("Arial", 12F, FontStyle.Bold, GraphicsUnit.Pixel);
    }
}

这个 LoadData() / code>方法在Form的构造函数中调用。列已创建,但其标题的更改不适用。
我认为它是因为我的循环中的缺陷 foreach(dgvBreakDowns.Rows中的DataGridViewHeaderCell标题)?我不知道。我尝试将其更改为 dgvBreakDowns.Columns ,并获得InvalidCastException。如何选择标题单元格应用这些更改?

This LoadData() method is called in the Form's constructor. The Columns are created but their Headers' changes don't apply. I think its because of a flaw in my loop foreach (DataGridViewHeaderCell header in dgvBreakDowns.Rows)? I'm not sure. I tried changing it to dgvBreakDowns.Columns and I get an InvalidCastException. How can I select the Header Cells to apply those changes?

我还有一个小问题。当我运行程序时,看起来像这样。

I have another minor issue. When I run the program it looks like this.

请注意,默认情况下,第一个单元格被选中,因此它显示为蓝色。当然它不影响任何东西,但它看起来有点丑陋和不整洁。可以阻止它选择这样的单元格?

Notice the first Cell is selected by default therefore it appears Blue. Sure it doesn't affect anything but it just looks somewhat ugly and untidy. It is possible to stop it from selecting the Cell like that?

推荐答案

尝试这个(注意我在这里使用列行):

Try this (note I'm using Columns here and not Rows):

foreach(DataGridViewColumn col in dgvBreakDowns.Columns)
{
    col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
    col.HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Bold, GraphicsUnit.Pixel);
}

关于取消选择单元格,请尝试 dgvBreakDowns.ClearSelection()

As for deselecting the cell, try dgvBreakDowns.ClearSelection()

这篇关于更改DataGridView标题单元格的文本对齐和字体大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆