DataGridViewCellStyle 클래스

정의

DataGridView 컨트롤 내에서 개별 셀에 적용된 서식 및 스타일 정보를 나타냅니다.

public ref class DataGridViewCellStyle : ICloneable
[System.ComponentModel.TypeConverter(typeof(System.Windows.Forms.DataGridViewCellStyleConverter))]
public class DataGridViewCellStyle : ICloneable
[<System.ComponentModel.TypeConverter(typeof(System.Windows.Forms.DataGridViewCellStyleConverter))>]
type DataGridViewCellStyle = class
    interface ICloneable
Public Class DataGridViewCellStyle
Implements ICloneable
상속
DataGridViewCellStyle
특성
구현

예제

다음 코드 예제에서는 여러 DataGridViewCellStyle 개체에 속성을 설정의 효과 보여 줍니다. 다음은 속성의 속성을 설정하여 의 DataGridView 셀 배경색을 BackColor 설정하는 예제입니다 DefaultCellStyle . 속성이 속성에 설정되어 있기 때문에 번갈아 행에서 배경색이 재정의 BackColorAlternatingRowsDefaultCellStyle 됩니다. 이 예제에서는 열의 속성에서 속성을 설정 Format 하여 명명된 Last Prepared 열의 DefaultCellStyle 날짜 형식도 결정합니다.

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

설명

클래스를 DataGridViewCellStyle 사용하면 여러 DataGridView 셀, 행, 열, 행 또는 열 머리글 간에 스타일 정보를 공유할 수 있으므로 개별 셀에서 스타일 속성을 설정하는 메모리 요구 사항을 방지할 수 있습니다. 형식 DataGridViewCellStyle 의 속성이 있는 클래스와 클래스가 서로 어떻게 관련되는지에 대한 자세한 내용은 Windows Forms DataGridView 컨트롤의 셀 스타일을 참조하세요.

생성자

DataGridViewCellStyle()

기본 속성 값을 사용하여 DataGridViewCellStyle 클래스의 새 인스턴스를 초기화합니다.

DataGridViewCellStyle(DataGridViewCellStyle)

지정된 DataGridViewCellStyle의 속성 값을 사용하여 DataGridViewCellStyle 클래스의 새 인스턴스를 초기화합니다.

속성

Alignment

DataGridView 셀에서 셀 내용의 위치를 나타내는 값을 가져오거나 설정합니다.

BackColor

DataGridView 셀의 배경색을 가져오거나 설정합니다.

DataSourceNullValue

사용자가 셀에 null 값을 입력할 때 데이터 소스에 저장된 값을 가져오거나 설정합니다.

Font

DataGridView 셀의 텍스트 콘텐츠에 적용된 글꼴을 가져오거나 설정합니다.

ForeColor

DataGridView 셀의 전경색을 가져오거나 설정합니다.

Format

DataGridView 셀의 텍스트 콘텐츠에 적용된 서식 문자열을 가져오거나 설정합니다.

FormatProvider

DataGridView 셀 값의 문화권별 서식 지정을 제공하는 데 사용되는 개체를 가져오거나 설정합니다.

IsDataSourceNullValueDefault

DataSourceNullValue 속성이 설정되었는지 여부를 나타내는 값을 가져옵니다.

IsFormatProviderDefault

FormatProvider 속성이 설정되었는지 여부를 나타내는 값을 가져옵니다.

IsNullValueDefault

NullValue 속성이 설정되었는지 여부를 나타내는 값을 가져옵니다.

NullValue

DataGridView 또는 null의 셀 값에 해당하는 Value 셀 표시 값을 가져오거나 설정합니다.

Padding

DataGridViewCell의 가장자리와 내용 사이의 간격을 가져오거나 설정합니다.

SelectionBackColor

선택된 DataGridView 셀에서 사용할 배경색을 가져오거나 설정합니다.

SelectionForeColor

선택된 DataGridView 셀에서 사용할 전경색을 가져오거나 설정합니다.

Tag

DataGridViewCellStyle과 관련된 추가 데이터가 포함된 개체를 가져오거나 설정합니다.

WrapMode

DataGridView 셀의 텍스트 콘텐츠가 한 줄에 들어가지 않을 정도로 긴 경우 텍스트 콘텐츠가 다음 줄로 줄 바꿈되는지 또는 잘리는지 여부를 나타내는 값을 가져오거나 설정합니다.

메서드

ApplyStyle(DataGridViewCellStyle)

지정된 DataGridViewCellStyle을 현재 DataGridViewCellStyle에 적용합니다.

Clone()

DataGridViewCellStyle의 정확한 복사본을 만듭니다.

Equals(Object)

이 인스턴스가 지정된 개체와 같은지 여부를 나타내는 값을 반환합니다.

GetHashCode()

특정 유형에 대한 해시 함수로 사용합니다.

GetType()

현재 인스턴스의 Type을 가져옵니다.

(다음에서 상속됨 Object)
MemberwiseClone()

현재 Object의 단순 복사본을 만듭니다.

(다음에서 상속됨 Object)
ToString()

DataGridViewCellStyle의 현재 속성 설정을 나타내는 문자열을 반환합니다.

명시적 인터페이스 구현

ICloneable.Clone()

DataGridViewCellStyle의 정확한 복사본을 만듭니다.

적용 대상

추가 정보