如何:設定 Windows Form DataGridView 控制項的字型和色彩樣式

您可以設定 DataGridViewCellStyle 類別的屬性,在 DataGridView 控制項內指定儲存格的視覺外觀。 您可以從 DataGridView 類別和其附屬類別的各種屬性擷取此類別的執行個體,或者您可以具現化 DataGridViewCellStyle 物件以便指派給這些屬性。

下列程序將示範使用 DefaultCellStyle 屬性進行儲存格外觀的基本自訂。 控制項中的每個儲存格會透過這個屬性繼承指定的樣式,除非它們在資料行、資料列,或儲存格層級遭到覆寫。 如需樣式繼承的範例,請參閱 如何:設定 Windows Forms DataGridView 控制項 的預設儲存格樣式。 如需 DataGridViewCellStyle 類別其他用法的相關資訊,請參閱<另請參閱>一節中所列的主題。

在 Visual Studio 中對於本工作有更詳盡的支援。 另請參閱 如何:使用設計 工具設定 Windows Forms 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 Forms DataGridView 控制項 的最佳做法。

另請參閱