如何:在 Windows 窗体 DataGridView 控件中设置字体和颜色样式

可以通过设置 DataGridViewCellStyle 类的属性,指定 DataGridView 控件内单元格的可视外观。 可以从 DataGridView 类及其伴生类的各个属性检索此类的实例,或可实例化 DataGridViewCellStyle 对象以分配到这些属性。

以下步骤演示使用 DefaultCellStyle 属性进行单元格外观的基本自定义。 控件中每个单元格将继承通过此属性指定的样式,除非它们在列、行或单元格级别中重写。 有关样式继承的示例,请参阅如何:设置 Windows 窗体 DataGridView 控件的默认单元格样式。 有关的 DataGridViewCellStyle 类更多用法的信息,请参阅“另请参阅”部分中列出的主题。

Visual Studio 中对此任务提供广泛支持。 另请参阅如何:使用设计器设置 Windows 窗体 DataGridView 控件的默认单元格样式和数据格式

若要指定 DataGridView 单元格所使用的字体

  • 设置 DataGridViewCellStyleFont 属性。 以下代码示例使用 DataGridView.DefaultCellStyle 属性设置整个控件的字体。

    this.dataGridView1.DefaultCellStyle.Font = new Font("Tahoma", 15);
    
    Me.dataGridView1.DefaultCellStyle.Font = New Font("Tahoma", 15)
    

若要指定 DataGridView 单元格的前景色和背景色

  • 设置 DataGridViewCellStyleForeColorBackColor 属性。 以下代码示例使用 DataGridView.DefaultCellStyle 属性为整个控件设置此类样式。

    this.dataGridView1.DefaultCellStyle.ForeColor = Color.Blue;
    this.dataGridView1.DefaultCellStyle.BackColor = Color.Beige;
    
    Me.dataGridView1.DefaultCellStyle.ForeColor = Color.Blue
    Me.dataGridView1.DefaultCellStyle.BackColor = Color.Beige
    

若要指定选定 DataGridView 单元格的前景色和背景色

  • 设置 DataGridViewCellStyleSelectionForeColorSelectionBackColor 属性。 以下代码示例使用 DataGridView.DefaultCellStyle 属性为整个控件设置此类样式。

    this.dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Yellow;
    this.dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Black;
    
    Me.dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Yellow
    Me.dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Black
    

示例

private void SetFontAndColors()
{
    this.dataGridView1.DefaultCellStyle.Font = new Font("Tahoma", 15);
    this.dataGridView1.DefaultCellStyle.ForeColor = Color.Blue;
    this.dataGridView1.DefaultCellStyle.BackColor = Color.Beige;
    this.dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Yellow;
    this.dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Black;
}
Private Sub SetFontAndColors()

    With Me.dataGridView1.DefaultCellStyle
        .Font = New Font("Tahoma", 15)
        .ForeColor = Color.Blue
        .BackColor = Color.Beige
        .SelectionForeColor = Color.Yellow
        .SelectionBackColor = Color.Black
    End With

End Sub

编译代码

此示例需要:

可靠编程

为实现最大的可伸缩性,应在使用相同样式的多个行、列或单元格间共享 DataGridViewCellStyle 对象,而不是分别设置单个元素的样式属性。 有关详细信息,请参阅 缩放 Windows 窗体 DataGridView 控件的最佳做法

另请参阅