共用方式為


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

更新:2007 年 11 月

您可以藉由設定 DataGridViewCellStyle 類別的屬性,指定 DataGridView 控制項中儲存格的視覺外觀。您可以從 DataGridView 類別及其從屬類別的數個屬性擷取此類別的執行個體,或者可以為這些屬性的指派具現化 DataGridViewCellStyle 物件。

下列程序使用 DefaultCellStyle 屬性來示範儲存格外觀的基本自訂。控制項中的每個儲存格都會繼承透過這個屬性所指定的樣式,除非在資料行、資料列或儲存格層級中覆寫了這些樣式。如需樣式繼承的範例,請參閱 HOW TO:設定 Windows Form DataGridView 控制項的預設儲存格樣式。如需其他使用 DataGridViewCellStyle 類別的詳細資訊,請參閱列於<請參閱>章節的主題。

Visual Studio 中對此工作有相當廣泛的支援。

若要指定 DataGridView 儲存格所使用的字型

  • 設定 DataGridViewCellStyleFont 屬性。下列程式碼範例使用 DataGridView.DefaultCellStyle 屬性為整個控制項設定字型。

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

若要指定 DataGridView 儲存格的前景和背景色彩

  • 設定 DataGridViewCellStyleForeColorBackColor 屬性。下列程式碼範例使用 DataGridView.DefaultCellStyle 屬性為整個控制項設定這些樣式。

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

若要指定選取的 DataGridView 儲存格的前景和背景色彩

  • 設定 DataGridViewCellStyleSelectionForeColorSelectionBackColor 屬性。下列程式碼範例使用 DataGridView.DefaultCellStyle 屬性為整個控制項設定這些樣式。

    Me.dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Yellow
    Me.dataGridView1.DefaultCellStyle.SelectionBackColor = Color.Black
    
    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
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;
}

編譯程式碼

這個範例需要:

穩固程式設計

對於最大延展性,您應該共用使用相同樣式的多個資料列、資料行或儲存格之間的 DataGridViewCellStyle 物件,而不是為每一個項目分別設定樣式屬性。如需詳細資訊,請參閱縮放 Windows Form DataGridView 控制項的最佳作法

請參閱

概念

Windows Form DataGridView 控制項中的儲存格樣式

參考

DataGridView.DefaultCellStyle

DataGridViewCellStyle

其他資源

Windows Form DataGridView 控制項中的基本格式化和樣式設定