DataGridViewCellStyle DataGridViewCellStyle DataGridViewCellStyle DataGridViewCellStyle Class

定義

表示套用至 DataGridView 控制項內個別儲存格的格式化和樣式資訊。Represents the formatting and style information applied to individual cells within a DataGridView control.

public ref class DataGridViewCellStyle : ICloneable
[System.ComponentModel.TypeConverter(typeof(System.Windows.Forms.DataGridViewCellStyleConverter))]
public class DataGridViewCellStyle : ICloneable
type DataGridViewCellStyle = class
    interface ICloneable
Public Class DataGridViewCellStyle
Implements ICloneable
繼承
DataGridViewCellStyleDataGridViewCellStyleDataGridViewCellStyleDataGridViewCellStyle
屬性
實作

範例

下列程式碼範例示範在多個DataGridViewCellStyle物件上設定屬性的效果。The following code example demonstrates the effect of setting properties on multiple DataGridViewCellStyle objects. 這個範例會在DataGridView DefaultCellStyle屬性上BackColor設定屬性, 藉以在中設定儲存格的背景色彩。This example sets the background color of cells in the DataGridView by setting the BackColor property on the DefaultCellStyle property. 因為屬性是在BackColor AlternatingRowsDefaultCellStyle屬性上設定, 所以在替代資料列上會覆寫背景色彩。The background color is overridden on alternating rows because the BackColor property is set on the AlternatingRowsDefaultCellStyle property. 此範例也會藉Last Prepared由在資料行的DefaultCellStyle屬性上Format設定屬性, 來判斷資料行中日期的格式。The example also determines the format of dates in the column named Last Prepared by setting the Format property on the column's DefaultCellStyle property.

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;

public class Form1 : System.Windows.Forms.Form
{
    [STAThreadAttribute()]
    public static void Main()
    {
        Application.Run(new Form1());
    }

    private DataGridView dataGridView1 = new DataGridView();

    protected override void OnLoad(EventArgs e)
    {
        // Create the columns and load the data.
        PopulateDataGridView();

        // Configure the appearance and behavior of the DataGridView.
        InitializeDataGridView();

        // Initialize the form.
        this.Text = "DataGridView style demo";
        this.Size = new Size(600, 250);
        this.Controls.Add(dataGridView1);
        base.OnLoad(e);
    }

    // Configures the appearance and behavior of a DataGridView control.
    private void InitializeDataGridView()
    {
        // Initialize basic DataGridView properties.
        dataGridView1.Dock = DockStyle.Fill;
        dataGridView1.BackgroundColor = Color.LightGray;
        dataGridView1.BorderStyle = BorderStyle.Fixed3D;

        // Set property values appropriate for read-only display and 
        // limited interactivity. 
        dataGridView1.AllowUserToAddRows = false;
        dataGridView1.AllowUserToDeleteRows = false;
        dataGridView1.AllowUserToOrderColumns = true;
        dataGridView1.ReadOnly = true;
        dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        dataGridView1.MultiSelect = false;
        dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
        dataGridView1.AllowUserToResizeColumns = false;
        dataGridView1.ColumnHeadersHeightSizeMode = 
            DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
        dataGridView1.AllowUserToResizeRows = false;
        dataGridView1.RowHeadersWidthSizeMode = 
            DataGridViewRowHeadersWidthSizeMode.DisableResizing;

        // Set the selection background color for all the cells.
        dataGridView1.DefaultCellStyle.SelectionBackColor = Color.White;
        dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Black;

        // Set RowHeadersDefaultCellStyle.SelectionBackColor so that its default
        // value won't override DataGridView.DefaultCellStyle.SelectionBackColor.
        dataGridView1.RowHeadersDefaultCellStyle.SelectionBackColor = Color.Empty;

        // Set the background color for all rows and for alternating rows. 
        // The value for alternating rows overrides the value for all rows. 
        dataGridView1.RowsDefaultCellStyle.BackColor = Color.LightGray;
        dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.DarkGray;

        // Set the row and column header styles.
        dataGridView1.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
        dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Black;
        dataGridView1.RowHeadersDefaultCellStyle.BackColor = Color.Black;

        // Set the Format property on the "Last Prepared" column to cause
        // the DateTime to be formatted as "Month, Year".
        dataGridView1.Columns["Last Prepared"].DefaultCellStyle.Format = "y";

        // Specify a larger font for the "Ratings" column. 
        using (Font font = new Font(
            dataGridView1.DefaultCellStyle.Font.FontFamily, 25, FontStyle.Bold))
        {
            dataGridView1.Columns["Rating"].DefaultCellStyle.Font = font;
        }

        // Attach a handler to the CellFormatting event.
        dataGridView1.CellFormatting += new
            DataGridViewCellFormattingEventHandler(dataGridView1_CellFormatting);
    }

    // Changes the foreground color of cells in the "Ratings" column 
    // depending on the number of stars. 
    private void dataGridView1_CellFormatting(object sender,
        DataGridViewCellFormattingEventArgs e)
    {
        if (e.ColumnIndex == dataGridView1.Columns["Rating"].Index
            && e.Value != null)
        {
            switch (e.Value.ToString().Length)
            {
                case 1:
                    e.CellStyle.SelectionForeColor = Color.Red;
                    e.CellStyle.ForeColor = Color.Red;
                    break;
                case 2:
                    e.CellStyle.SelectionForeColor = Color.Yellow;
                    e.CellStyle.ForeColor = Color.Yellow;
                    break;
                case 3:
                    e.CellStyle.SelectionForeColor = Color.Green;
                    e.CellStyle.ForeColor = Color.Green;
                    break;
                case 4:
                    e.CellStyle.SelectionForeColor = Color.Blue;
                    e.CellStyle.ForeColor = Color.Blue;
                    break;
            }
        }
    }

    // Creates the columns and loads the data.
    private void PopulateDataGridView()
    {
        // Set the column header names.
        dataGridView1.ColumnCount = 5;
        dataGridView1.Columns[0].Name = "Recipe";
        dataGridView1.Columns[1].Name = "Category";
        dataGridView1.Columns[2].Name = "Main Ingredients";
        dataGridView1.Columns[3].Name = "Last Prepared";
        dataGridView1.Columns[4].Name = "Rating";

        // Populate the rows.
        object[] row1 = new object[]{"Meatloaf", "Main Dish", 
            "ground beef", new DateTime(2000, 3, 23), "*"};
        object[] row2 = new object[]{"Key Lime Pie", "Dessert", 
            "lime juice, evaporated milk", new DateTime(2002, 4, 12), "****"};
        object[] row3 = new object[]{"Orange-Salsa Pork Chops", "Main Dish", 
            "pork chops, salsa, orange juice", new DateTime(2000, 8, 9), "****"};
        object[] row4 = new object[]{"Black Bean and Rice Salad", "Salad", 
            "black beans, brown rice", new DateTime(1999, 5, 7), "****"};
        object[] row5 = new object[]{"Chocolate Cheesecake", "Dessert", 
            "cream cheese", new DateTime(2003, 3, 12), "***"};
        object[] row6 = new object[]{"Black Bean Dip", "Appetizer",
            "black beans, sour cream", new DateTime(2003, 12, 23), "***"};

        // Add the rows to the DataGridView.
        object[] rows = new object[] { row1, row2, row3, row4, row5, row6 };
        foreach (object[] rowArray in rows)
        {
            dataGridView1.Rows.Add(rowArray);
        }

        // Adjust the row heights so that all content is visible.
        dataGridView1.AutoResizeRows(
            DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders);
    }

}
Imports System.Drawing
Imports System.Collections
Imports System.ComponentModel
Imports System.Windows.Forms

Public Class Form1
    Inherits System.Windows.Forms.Form

    <STAThreadAttribute()> _
    Public Shared Sub Main()
        Application.Run(New Form1())
    End Sub

    Private WithEvents dataGridView1 As New DataGridView()

    Protected Overrides Sub OnLoad(ByVal e As EventArgs)

        ' Create the columns and load the data.
        PopulateDataGridView()

        ' Configure the appearance and behavior of the DataGridView.
        InitializeDataGridView()

        ' Initialize the form.
        Me.Text = "DataGridView style demo"
        Me.Size = New Size(600, 250)
        Me.Controls.Add(dataGridView1)
        MyBase.OnLoad(e)

    End Sub

    ' Configures the appearance and behavior of a DataGridView control.
    Private Sub InitializeDataGridView()

        ' Initialize basic DataGridView properties.
        dataGridView1.Dock = DockStyle.Fill
        dataGridView1.BackgroundColor = Color.LightGray
        dataGridView1.BorderStyle = BorderStyle.Fixed3D

        ' Set property values appropriate for read-only display and 
        ' limited interactivity. 
        dataGridView1.AllowUserToAddRows = False
        dataGridView1.AllowUserToDeleteRows = False
        dataGridView1.AllowUserToOrderColumns = True
        dataGridView1.ReadOnly = True
        dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect
        dataGridView1.MultiSelect = False
        dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None
        dataGridView1.AllowUserToResizeColumns = False
        dataGridView1.ColumnHeadersHeightSizeMode = _
            DataGridViewColumnHeadersHeightSizeMode.DisableResizing
        dataGridView1.AllowUserToResizeRows = False
        dataGridView1.RowHeadersWidthSizeMode = _
            DataGridViewRowHeadersWidthSizeMode.DisableResizing

        ' Set the selection background color for all the cells.
        dataGridView1.DefaultCellStyle.SelectionBackColor = Color.White
        dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Black

        ' Set RowHeadersDefaultCellStyle.SelectionBackColor so that its default
        ' value won't override DataGridView.DefaultCellStyle.SelectionBackColor.
        dataGridView1.RowHeadersDefaultCellStyle.SelectionBackColor = Color.Empty

        ' Set the background color for all rows and for alternating rows. 
        ' The value for alternating rows overrides the value for all rows. 
        dataGridView1.RowsDefaultCellStyle.BackColor = Color.LightGray
        dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.DarkGray

        ' Set the row and column header styles.
        dataGridView1.ColumnHeadersDefaultCellStyle.ForeColor = Color.White
        dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Black
        dataGridView1.RowHeadersDefaultCellStyle.BackColor = Color.Black

        ' Set the Format property on the "Last Prepared" column to cause
        ' the DateTime to be formatted as "Month, Year".
        dataGridView1.Columns("Last Prepared").DefaultCellStyle.Format = "y"

        ' Specify a larger font for the "Ratings" column. 
        Dim font As New Font( _
            dataGridView1.DefaultCellStyle.Font.FontFamily, 25, FontStyle.Bold)
        Try
            dataGridView1.Columns("Rating").DefaultCellStyle.Font = font
        Finally
            font.Dispose()
        End Try

    End Sub

    ' Changes the foreground color of cells in the "Ratings" column 
    ' depending on the number of stars. 
    Private Sub dataGridView1_CellFormatting(ByVal sender As Object, _
        ByVal e As DataGridViewCellFormattingEventArgs) _
        Handles dataGridView1.CellFormatting

        If e.ColumnIndex = dataGridView1.Columns("Rating").Index _
            AndAlso e.Value IsNot Nothing Then

            Select Case e.Value.ToString().Length
                Case 1
                    e.CellStyle.SelectionForeColor = Color.Red
                    e.CellStyle.ForeColor = Color.Red
                Case 2
                    e.CellStyle.SelectionForeColor = Color.Yellow
                    e.CellStyle.ForeColor = Color.Yellow
                Case 3
                    e.CellStyle.SelectionForeColor = Color.Green
                    e.CellStyle.ForeColor = Color.Green
                Case 4
                    e.CellStyle.SelectionForeColor = Color.Blue
                    e.CellStyle.ForeColor = Color.Blue
            End Select

        End If

    End Sub

    ' Creates the columns and loads the data.
    Private Sub PopulateDataGridView()

        ' Set the column header names.
        dataGridView1.ColumnCount = 5
        dataGridView1.Columns(0).Name = "Recipe"
        dataGridView1.Columns(1).Name = "Category"
        dataGridView1.Columns(2).Name = "Main Ingredients"
        dataGridView1.Columns(3).Name = "Last Prepared"
        dataGridView1.Columns(4).Name = "Rating"

        ' Populate the rows.
        Dim row1() As Object = {"Meatloaf", "Main Dish", _
            "ground beef", New DateTime(2000, 3, 23), "*"}
        Dim row2() As Object = {"Key Lime Pie", "Dessert", _
            "lime juice, evaporated milk", New DateTime(2002, 4, 12), "****"}
        Dim row3() As Object = {"Orange-Salsa Pork Chops", "Main Dish", _
            "pork chops, salsa, orange juice", New DateTime(2000, 8, 9), "****"}
        Dim row4() As Object = {"Black Bean and Rice Salad", "Salad", _
            "black beans, brown rice", New DateTime(1999, 5, 7), "****"}
        Dim row5() As Object = {"Chocolate Cheesecake", "Dessert", _
            "cream cheese", New DateTime(2003, 3, 12), "***"}
        Dim row6() As Object = {"Black Bean Dip", "Appetizer", _
            "black beans, sour cream", New DateTime(2003, 12, 23), "***"}

        ' Add the rows to the DataGridView.
        Dim rows() As Object = {row1, row2, row3, row4, row5, row6}
        Dim rowArray As Object()
        For Each rowArray In rows
            dataGridView1.Rows.Add(rowArray)
        Next rowArray

        ' Adjust the row heights so that all content is visible.
        dataGridView1.AutoResizeRows( _
            DataGridViewAutoSizeRowsMode.AllCellsExceptHeaders)

    End Sub
End Class

備註

類別可讓您在多個DataGridView資料格、資料列、資料行和資料列或資料行標頭之間共用樣式資訊, 避免在個別資料格上設定樣式屬性的記憶體需求。 DataGridViewCellStyleThe DataGridViewCellStyle class lets you share style information across multiple DataGridView cells, rows, columns, and row or column headers, avoiding the memory requirements of setting style properties on individual cells. 如需具有類型DataGridViewCellStyle之屬性的類別, 以及它們彼此之間如何相互關聯的詳細資訊, 請參閱Windows Forms DataGridView 控制項中的儲存格樣式For more information about classes that have a property of type DataGridViewCellStyle and how they relate to each other, see Cell Styles in the Windows Forms DataGridView Control.

建構函式

DataGridViewCellStyle() DataGridViewCellStyle() DataGridViewCellStyle() DataGridViewCellStyle()

使用預設的屬性值,初始化 DataGridViewCellStyle 類別的新執行個體。Initializes a new instance of the DataGridViewCellStyle class using default property values.

DataGridViewCellStyle(DataGridViewCellStyle) DataGridViewCellStyle(DataGridViewCellStyle) DataGridViewCellStyle(DataGridViewCellStyle) DataGridViewCellStyle(DataGridViewCellStyle)

使用指定之 DataGridViewCellStyle 的屬性值來初始化 DataGridViewCellStyle 類別的新執行個體。Initializes a new instance of the DataGridViewCellStyle class using the property values of the specified DataGridViewCellStyle.

屬性

Alignment Alignment Alignment Alignment

取得或設定值,表示 DataGridView 儲存格內儲存格內容的位置。Gets or sets a value indicating the position of the cell content within a DataGridView cell.

BackColor BackColor BackColor BackColor

取得或設定 DataGridView 儲存格的背景色彩。Gets or sets the background color of a DataGridView cell.

DataSourceNullValue DataSourceNullValue DataSourceNullValue DataSourceNullValue

取得或設定當使用者輸入 null 值到儲存格時儲存到資料來源中的值。Gets or sets the value saved to the data source when the user enters a null value into a cell.

Font Font Font Font

取得或設定 DataGridView 儲存格的文字內容所套用的字型。Gets or sets the font applied to the textual content of a DataGridView cell.

ForeColor ForeColor ForeColor ForeColor

取得或設定 DataGridView 儲存格的前景色彩。Gets or sets the foreground color of a DataGridView cell.

Format Format Format Format

取得或設定 DataGridView 儲存格的文字內容所套用的格式字串。Gets or sets the format string applied to the textual content of a DataGridView cell.

FormatProvider FormatProvider FormatProvider FormatProvider

取得或設定用來提供文化特性特有的 DataGridView 儲存格值格式的物件。Gets or sets the object used to provide culture-specific formatting of DataGridView cell values.

IsDataSourceNullValueDefault IsDataSourceNullValueDefault IsDataSourceNullValueDefault IsDataSourceNullValueDefault

取得指出是否已經設定 DataSourceNullValue 屬性的值。Gets a value indicating whether the DataSourceNullValue property has been set.

IsFormatProviderDefault IsFormatProviderDefault IsFormatProviderDefault IsFormatProviderDefault

取得值,指出是否已經設定 FormatProvider 屬性。Gets a value that indicates whether the FormatProvider property has been set.

IsNullValueDefault IsNullValueDefault IsNullValueDefault IsNullValueDefault

取得指出是否已經設定 NullValue 屬性的值。Gets a value indicating whether the NullValue property has been set.

NullValue NullValue NullValue NullValue

取得或設定 DataGridView 儲存格顯示值,這個值會對應到 Value 的儲存格值或 nullGets or sets the DataGridView cell display value corresponding to a cell value of Value or null.

Padding Padding Padding Padding

取得或設定介於 DataGridViewCell 的邊緣與其內容之間的空格。Gets or sets the space between the edge of a DataGridViewCell and its content.

SelectionBackColor SelectionBackColor SelectionBackColor SelectionBackColor

取得或設定當選取 DataGridView 儲存格時,由該儲存格使用的背景色彩。Gets or sets the background color used by a DataGridView cell when it is selected.

SelectionForeColor SelectionForeColor SelectionForeColor SelectionForeColor

取得或設定當選取 DataGridView 儲存格時,由該儲存格使用的前景色彩。Gets or sets the foreground color used by a DataGridView cell when it is selected.

Tag Tag Tag Tag

取得或設定物件,這個物件包含與 DataGridViewCellStyle 相關的其他資料。Gets or sets an object that contains additional data related to the DataGridViewCellStyle.

WrapMode WrapMode WrapMode WrapMode

取得或設定值,指出當 DataGridView 儲存格中的文字內容太長而無法置於一行時,是否要將它換行或截斷它。Gets or sets a value indicating whether textual content in a DataGridView cell is wrapped to subsequent lines or truncated when it is too long to fit on a single line.

方法

ApplyStyle(DataGridViewCellStyle) ApplyStyle(DataGridViewCellStyle) ApplyStyle(DataGridViewCellStyle) ApplyStyle(DataGridViewCellStyle)

將指定的 DataGridViewCellStyle 套用到目前的 DataGridViewCellStyleApplies the specified DataGridViewCellStyle to the current DataGridViewCellStyle.

Clone() Clone() Clone() Clone()

建立這個 DataGridViewCellStyle 的完全相同複本。Creates an exact copy of this DataGridViewCellStyle.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

傳回值,指出此執行個體是否相當於指定的物件。Returns a value indicating whether this instance is equivalent to the specified object.

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

做為特定型別的雜湊函式。Serves as a hash function for a particular type.

GetType() GetType() GetType() GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(Inherited from Object)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(Inherited from Object)
ToString() ToString() ToString() ToString()

傳回字串,此字串表示 DataGridViewCellStyle 目前的屬性設定。Returns a string indicating the current property settings of the DataGridViewCellStyle.

明確介面實作

ICloneable.Clone() ICloneable.Clone() ICloneable.Clone() ICloneable.Clone()

建立這個 DataGridViewCellStyle 的完全相同複本。Creates an exact copy of this DataGridViewCellStyle.

適用於

另請參閱