영어로 읽기

다음을 통해 공유


DataGridViewColumn 클래스

정의

DataGridView 컨트롤의 열을 나타냅니다.

C#
[System.ComponentModel.TypeConverter(typeof(System.Windows.Forms.DataGridViewColumnConverter))]
public class DataGridViewColumn : System.Windows.Forms.DataGridViewBand, IDisposable, System.ComponentModel.IComponent
상속
파생
특성
구현

예제

다음 코드 예제에서는 및 단추 집합을 DataGridView 사용하여 Windows Form을 만듭니다. 각 단추 레이블은 첫 번째 및 마지막 열 교환(속성 사용DisplayIndex) 또는 열 머리글 텍스트 변경(속성 사용HeaderText)과 같은 속성과 관련된 DataGridViewColumn 작업을 설명합니다. 단추를 클릭하면 의 연결된 속성이 DataGridViewColumn변경됩니다.

C#
using System.Windows.Forms;
using System;
using System.Drawing;

public class DataGridViewColumnDemo : Form
{
    #region "set up form"
    public DataGridViewColumnDemo()
    {
        InitializeComponent();

        AddButton(Button1, "Reset",
            new EventHandler(ResetToDisorder));
        AddButton(Button2, "Change Column 3 Header",
            new EventHandler(ChangeColumn3Header));
        AddButton(Button3, "Change Meatloaf Recipe",
            new EventHandler(ChangeMeatloafRecipe));
        AddAdditionalButtons();

        InitializeDataGridView();
    }

    DataGridView dataGridView;
    Button Button1 = new Button();
    Button Button2 = new Button();
    Button Button3 = new Button();
    Button Button4 = new Button();
    Button Button5 = new Button();
    Button Button6 = new Button();
    Button Button7 = new Button();
    Button Button8 = new Button();
    Button Button9 = new Button();
    Button Button10 = new Button();
    FlowLayoutPanel FlowLayoutPanel1 = new FlowLayoutPanel();

    private void InitializeComponent()
    {
        FlowLayoutPanel1.Location = new Point(454, 0);
        FlowLayoutPanel1.AutoSize = true;
        FlowLayoutPanel1.FlowDirection = FlowDirection.TopDown;
        FlowLayoutPanel1.Name = "flowlayoutpanel";
        ClientSize = new System.Drawing.Size(614, 360);
        Controls.Add(this.FlowLayoutPanel1);
        Text = this.GetType().Name;
        AutoSize = true;
    }
    #endregion

    #region "set up DataGridView"

    private string thirdColumnHeader = "Main Ingredients";
    private string boringMeatloaf = "ground beef";
    private string boringMeatloafRanking = "*";
    private bool boringRecipe;
    private bool shortMode;

    private void InitializeDataGridView()
    {
        dataGridView = new System.Windows.Forms.DataGridView();
        Controls.Add(dataGridView);
        dataGridView.Size = new Size(300, 200);

        // Create an unbound DataGridView by declaring a
        // column count.
        dataGridView.ColumnCount = 4;
        AdjustDataGridViewSizing();

        // Set the column header style.
        DataGridViewCellStyle columnHeaderStyle =
            new DataGridViewCellStyle();
        columnHeaderStyle.BackColor = Color.Aqua;
        columnHeaderStyle.Font =
            new Font("Verdana", 10, FontStyle.Bold);
        dataGridView.ColumnHeadersDefaultCellStyle =
            columnHeaderStyle;

        // Set the column header names.
        dataGridView.Columns[0].Name = "Recipe";
        dataGridView.Columns[1].Name = "Category";
        dataGridView.Columns[2].Name = thirdColumnHeader;
        dataGridView.Columns[3].Name = "Rating";

        PostColumnCreation();

        // Populate the rows.
        string[] row1 = new string[]{"Meatloaf", 
                                        "Main Dish", boringMeatloaf, boringMeatloafRanking};
        string[] row2 = new string[]{"Key Lime Pie", 
                                        "Dessert", "lime juice, evaporated milk", "****"};
        string[] row3 = new string[]{"Orange-Salsa Pork Chops", 
                                        "Main Dish", "pork chops, salsa, orange juice", "****"};
        string[] row4 = new string[]{"Black Bean and Rice Salad", 
                                        "Salad", "black beans, brown rice", "****"};
        string[] row5 = new string[]{"Chocolate Cheesecake", 
                                        "Dessert", "cream cheese", "***"};
        string[] row6 = new string[]{"Black Bean Dip", "Appetizer",
                                        "black beans, sour cream", "***"};
        object[] rows = new object[] { row1, row2, row3, row4, row5, row6 };

        foreach (string[] rowArray in rows)
        {
            dataGridView.Rows.Add(rowArray);
        }

        shortMode = false;
        boringRecipe = true;
    }

    private void AddButton(Button button, string buttonLabel,
        EventHandler handler)
    {
        FlowLayoutPanel1.Controls.Add(button);
        button.TabIndex = FlowLayoutPanel1.Controls.Count;
        button.Text = buttonLabel;
        button.AutoSize = true;
        button.Click += handler;
    }

    private void ResetToDisorder(object sender, System.EventArgs e)
    {
        Controls.Remove(dataGridView);
        dataGridView.Dispose();
        InitializeDataGridView();
    }

    private void ChangeColumn3Header(object sender,
        System.EventArgs e)
    {
        Toggle(ref shortMode);
        if (shortMode)
        { dataGridView.Columns[2].HeaderText = "S"; }
        else
        { dataGridView.Columns[2].HeaderText = thirdColumnHeader; }
    }

    private static void Toggle(ref bool toggleThis)
    {
        toggleThis = !toggleThis;
    }

    private void ChangeMeatloafRecipe(object sender,
        System.EventArgs e)
    {
        Toggle(ref boringRecipe);
        if (boringRecipe)
        {
            SetMeatloaf(boringMeatloaf, boringMeatloafRanking);
        }
        else
        {
            string greatMeatloafRecipe =
                "1 lb. lean ground beef, " +
                "1/2 cup bread crumbs, 1/4 cup ketchup," +
                "1/3 tsp onion powder, " +
                "1 clove of garlic, 1/2 pack onion soup mix " +
                " dash of your favorite BBQ Sauce";
            SetMeatloaf(greatMeatloafRecipe, "***");
        }
    }

    private void SetMeatloaf(string recipe, string rating)
    {
        dataGridView.Rows[0].Cells[2].Value = recipe;
        dataGridView.Rows[0].Cells[3].Value = rating;
    }
    #endregion

    #region "demonstration code"
    private void PostColumnCreation()
    {
        AddContextLabel();
        AddCriteriaLabel();
        CustomizeCellsInThirdColumn();
        AddContextMenu();
        SetDefaultCellInFirstColumn();
        ToolTips();

        dataGridView.CellMouseEnter +=
            dataGridView_CellMouseEnter;
        dataGridView.AutoSizeColumnModeChanged +=
            dataGridView_AutoSizeColumnModeChanged;
    }

    private string criteriaLabel = "Column 3 sizing criteria: ";
    private void AddCriteriaLabel()
    {
        AddLabelToPanelIfNotAlreadyThere(criteriaLabel,
            criteriaLabel +
            dataGridView.Columns[2].AutoSizeMode.ToString() +
            ".");
    }

    private void AddContextLabel()
    {
        string labelName = "label";
        AddLabelToPanelIfNotAlreadyThere(labelName,
            "Use shortcut menu to change cell color.");
    }

    private void AddLabelToPanelIfNotAlreadyThere(
        string labelName, string labelText)
    {
        Label label;
        if (FlowLayoutPanel1.Controls[labelName] == null)
        {
            label = new Label();
            label.AutoSize = true;
            label.Name = labelName;
            label.BackColor = Color.Bisque;
            FlowLayoutPanel1.Controls.Add(label);
        }
        else
        {
            label = (Label)FlowLayoutPanel1.Controls[labelName];
        }
        label.Text = labelText;
    }

    private void CustomizeCellsInThirdColumn()
    {
        int thirdColumn = 2;
        DataGridViewColumn column =
            dataGridView.Columns[thirdColumn];
        DataGridViewCell cell = new DataGridViewTextBoxCell();

        cell.Style.BackColor = Color.Wheat;
        column.CellTemplate = cell;
    }

    ToolStripMenuItem toolStripItem1 = new ToolStripMenuItem();

    private void AddContextMenu()
    {
        toolStripItem1.Text = "Redden";
        toolStripItem1.Click += new EventHandler(toolStripItem1_Click);
        ContextMenuStrip strip = new ContextMenuStrip();
        foreach (DataGridViewColumn column in dataGridView.Columns)
        {

            column.ContextMenuStrip = strip;
            column.ContextMenuStrip.Items.Add(toolStripItem1);
        }
    }

    private DataGridViewCellEventArgs mouseLocation;

    // Change the cell's color.
    private void toolStripItem1_Click(object sender, EventArgs args)
    {
        dataGridView.Rows[mouseLocation.RowIndex]
            .Cells[mouseLocation.ColumnIndex].Style.BackColor
            = Color.Red;
    }

    // Deal with hovering over a cell.
    private void dataGridView_CellMouseEnter(object sender,
        DataGridViewCellEventArgs location)
    {
        mouseLocation = location;
    }

    private void SetDefaultCellInFirstColumn()
    {
        DataGridViewColumn firstColumn = dataGridView.Columns[0];
        DataGridViewCellStyle cellStyle =
            new DataGridViewCellStyle();
        cellStyle.BackColor = Color.Thistle;

        firstColumn.DefaultCellStyle = cellStyle;
    }

    private void ToolTips()
    {
        DataGridViewColumn firstColumn = dataGridView.Columns[0];
        DataGridViewColumn thirdColumn = dataGridView.Columns[2];
        firstColumn.ToolTipText =
            "This column uses a default cell.";
        thirdColumn.ToolTipText =
            "This column uses a template cell." +
            " Style changes to one cell apply to all cells.";
    }

    private void AddAdditionalButtons()
    {
        AddButton(Button4, "Set Minimum Width of Column Two",
            new EventHandler(Button4_Click));
        AddButton(Button5, "Set Width of Column One",
            new EventHandler(Button5_Click));
        AddButton(Button6, "Autosize Third Column",
            new EventHandler(Button6_Click));
        AddButton(Button7, "Add Thick Vertical Edge",
            new EventHandler(Button7_Click));
        AddButton(Button8, "Style and Number Columns",
            new EventHandler(Button8_Click));
        AddButton(Button9, "Change Column Header Text",
            new EventHandler(Button9_Click));
        AddButton(Button10, "Swap First and Last Columns",
            new EventHandler(Button10_Click));
    }

    private void AdjustDataGridViewSizing()
    {
        dataGridView.ColumnHeadersHeightSizeMode = 
            DataGridViewColumnHeadersHeightSizeMode.AutoSize;
    }

    //Set the minimum width.
    private void Button4_Click(object sender,
        System.EventArgs e)
    {
        DataGridViewColumn column = dataGridView.Columns[1];
        column.MinimumWidth = 40;
    }

    // Set the width.
    private void Button5_Click(object sender, System.EventArgs e)
    {
        DataGridViewColumn column = dataGridView.Columns[0];
        column.Width = 60;
    }

    // AutoSize the third column.
    private void Button6_Click(object sender,
        System.EventArgs e)
    {
        DataGridViewColumn column = dataGridView.Columns[2];
        column.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
    }

    // Set the vertical edge.
    private void Button7_Click(object sender,
        System.EventArgs e)
    {
        int thirdColumn = 2;
        DataGridViewColumn column =
            dataGridView.Columns[thirdColumn];
        column.DividerWidth = 10;
    }

    // Style and number columns.
    private void Button8_Click(object sender,
        EventArgs args)
    {
        DataGridViewCellStyle style = new DataGridViewCellStyle();
        style.Alignment =
            DataGridViewContentAlignment.MiddleCenter;
        style.ForeColor = Color.IndianRed;
        style.BackColor = Color.Ivory;

        foreach (DataGridViewColumn column in dataGridView.Columns)
        {
            column.HeaderCell.Value = column.Index.ToString();
            column.HeaderCell.Style = style;
        }
    }

    // Change the text in the column header.
    private void Button9_Click(object sender,
        EventArgs args)
    {
        foreach (DataGridViewColumn column in dataGridView.Columns)
        {

            column.HeaderText = String.Concat("Column ",
                column.Index.ToString());
        }
    }

    // Swap the last column with the first.
    private void Button10_Click(object sender, EventArgs args)
    {
        DataGridViewColumnCollection columnCollection = dataGridView.Columns;

        DataGridViewColumn firstVisibleColumn =
            columnCollection.GetFirstColumn(DataGridViewElementStates.Visible);
        DataGridViewColumn lastVisibleColumn =
            columnCollection.GetLastColumn(
                DataGridViewElementStates.Visible, DataGridViewElementStates.None);

        int firstColumn_sIndex = firstVisibleColumn.DisplayIndex;
        firstVisibleColumn.DisplayIndex = lastVisibleColumn.DisplayIndex;
        lastVisibleColumn.DisplayIndex = firstColumn_sIndex;
    }

    // Updated the criteria label.
    private void dataGridView_AutoSizeColumnModeChanged(object sender,
        DataGridViewAutoSizeColumnModeEventArgs args)
    {
        args.Column.DataGridView.Parent.
            Controls["flowlayoutpanel"].Controls[criteriaLabel].
            Text = criteriaLabel
            + args.Column.AutoSizeMode.ToString();
    }
    #endregion

    [STAThreadAttribute()]
    public static void Main()
    {
        Application.Run(new DataGridViewColumnDemo());
    }
}

설명

클래스는 DataGridViewColumn 컨트롤의 논리 열을 DataGridView 나타냅니다. 컨트롤의 컬렉션을 통해 열을 검색할 Columns 수 있습니다.

DataGridViewRow의 실제 셀 컬렉션을 포함하는 와 달리 열 너비 및 셀 DataGridViewDataGridViewColumn 스타일과 같은 UI(열 사용자 인터페이스)의 모양과 동작을 조정하는 데 주로 사용됩니다. 셀 스타일에 대한 자세한 내용은 Windows Forms DataGridView 컨트롤의 셀 스타일을 참조하세요.

에서 파생되는 형식은 일반적으로 속성을 클래스에서 DataGridViewColumnDataGridViewCell 파생된 관련 형식의 새 instance 초기화 CellTemplate 합니다. 개별 셀의 모양 또는 동작과 관련된 열 속성은 템플릿 셀의 해당 속성에 대한 래퍼입니다. 열에서 이러한 속성 중 하나를 변경하면 셀 템플릿 및 열의 모든 셀에 대한 값이 자동으로 변경됩니다. 열 값을 설정 하면 개별 셀에 대해 지정된 된 값을 재정의 하려면 셀 값을 설정 합니다.

상속자 참고

파생 하는 경우 DataGridViewColumn 파생된 클래스에 새 속성 추가 재정의 해야 합니다 Clone() 복제 작업 중 새 속성을 복사 하는 방법입니다. 또한 기본 클래스를 호출 해야 Clone() 메서드는 기본 클래스의 속성이 새로운 셀에 복사 되도록 합니다.

생성자

DataGridViewColumn()

DataGridViewColumn 클래스의 새 인스턴스를 기본 상태로 초기화합니다.

DataGridViewColumn(DataGridViewCell)

기존 DataGridViewColumn을 템플릿으로 사용하여 DataGridViewCell 클래스의 새 인스턴스를 초기화합니다.

속성

AutoSizeMode

열의 너비를 자동으로 조정하는 모드를 가져오거나 설정합니다.

CellTemplate

셀을 새로 만드는 데 사용되는 템플릿을 가져오거나 설정합니다.

CellType

셀 템플릿의 런타임 형식을 가져옵니다.

ContextMenuStrip

열의 바로 가기 메뉴를 가져오거나 설정합니다.

DataGridView

이 요소와 관련된 DataGridView 컨트롤을 가져옵니다.

(다음에서 상속됨 DataGridViewElement)
DataPropertyName

DataGridViewColumn이 바인딩되는 데이터베이스 열이나 데이터 소스 속성의 이름을 가져오거나 설정합니다.

DefaultCellStyle

열의 기본 셀 스타일을 가져오거나 설정합니다.

DefaultHeaderCellType

기본 머리글 셀의 런타임 형식을 가져오거나 설정합니다.

(다음에서 상속됨 DataGridViewBand)
Displayed

밴드가 현재 화면에 표시되는지 여부를 나타내는 값을 가져옵니다.

(다음에서 상속됨 DataGridViewBand)
DisplayIndex

현재 표시된 열에 상대적인 열의 표시 순서를 가져오거나 설정합니다.

DividerWidth

열 구분선의 너비(픽셀)를 가져오거나 설정합니다.

FillWeight

열이 컨트롤에 있는 다른 채우기 모드 열의 너비에 상대적인 채우기 모드에 있는 경우 열의 너비를 나타내는 값을 가져오거나 설정합니다.

Frozen

DataGridView 컨트롤을 가로로 스크롤하면 열이 이동할지 여부를 나타내는 값을 가져오거나 설정합니다.

HasDefaultCellStyle

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

(다음에서 상속됨 DataGridViewBand)
HeaderCell

열 머리글을 나타내는 DataGridViewColumnHeaderCell을 가져오거나 설정합니다.

HeaderCellCore

DataGridViewBand의 머리글 셀을 가져오거나 설정합니다.

(다음에서 상속됨 DataGridViewBand)
HeaderText

열의 머리글 셀에 있는 캡션 텍스트를 가져오거나 설정합니다.

Index

DataGridView 컨트롤에서 밴드의 상대적 위치를 가져옵니다.

(다음에서 상속됨 DataGridViewBand)
InheritedAutoSizeMode

열에 적용되는 크기 조정 모드를 가져옵니다.

InheritedStyle

열에 현재 적용된 셀 스타일을 가져옵니다.

IsDataBound

열이 데이터 소스에 바인딩되어 있는지 여부를 나타내는 값을 가져옵니다.

IsRow

밴드가 행을 나타내는지 여부를 나타내는 값을 가져옵니다.

(다음에서 상속됨 DataGridViewBand)
MinimumWidth

열의 최소 너비(픽셀)를 가져오거나 설정합니다.

Name

열 이름을 가져오거나 설정합니다.

ReadOnly

열의 셀을 편집할 수 있는지 여부를 나타내는 값을 가져오거나 설정합니다.

Resizable

열의 크기를 조정할 수 있는지 여부를 나타내는 값을 가져오거나 설정합니다.

Selected

밴드가 선택한 UI(사용자 인터페이스) 상태에 있는지 여부를 나타내는 값을 가져오거나 설정합니다.

(다음에서 상속됨 DataGridViewBand)
Site

열의 사이트를 가져오거나 설정합니다.

SortMode

열의 정렬 모드를 가져오거나 설정합니다.

State

요소의 UI(사용자 인터페이스) 상태를 가져옵니다.

(다음에서 상속됨 DataGridViewElement)
Tag

밴드에 연결할 데이터가 포함된 개체를 가져오거나 설정합니다.

(다음에서 상속됨 DataGridViewBand)
ToolTipText

도구 설명에 사용되는 텍스트를 가져오거나 설정합니다.

ValueType

열의 셀 값에 대한 데이터 형식을 가져오거나 설정합니다.

Visible

열이 표시되는지 여부를 나타내는 값을 가져오거나 설정합니다.

Width

열의 현재 너비를 가져오거나 설정합니다.

메서드

Clone()

이 밴드와 정확하게 일치하는 복사본을 만듭니다.

Dispose()

DataGridViewBand에서 사용하는 모든 리소스를 해제합니다.

(다음에서 상속됨 DataGridViewBand)
Dispose(Boolean)

DataGridViewBand에서 사용하는 관리되지 않는 리소스를 해제하고, 관리되는 리소스를 선택적으로 해제할 수 있습니다.

Equals(Object)

지정된 개체가 현재 개체와 같은지 확인합니다.

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

기본 해시 함수로 작동합니다.

(다음에서 상속됨 Object)
GetPreferredWidth(DataGridViewAutoSizeColumnMode, Boolean)

지정된 조건에 따라 열의 이상적인 너비를 계산합니다.

GetType()

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

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

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

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

밴드가 다른 DataGridView에 연결될 때 호출됩니다.

(다음에서 상속됨 DataGridViewBand)
RaiseCellClick(DataGridViewCellEventArgs)

CellClick 이벤트를 발생시킵니다.

(다음에서 상속됨 DataGridViewElement)
RaiseCellContentClick(DataGridViewCellEventArgs)

CellContentClick 이벤트를 발생시킵니다.

(다음에서 상속됨 DataGridViewElement)
RaiseCellContentDoubleClick(DataGridViewCellEventArgs)

CellContentDoubleClick 이벤트를 발생시킵니다.

(다음에서 상속됨 DataGridViewElement)
RaiseCellValueChanged(DataGridViewCellEventArgs)

CellValueChanged 이벤트를 발생시킵니다.

(다음에서 상속됨 DataGridViewElement)
RaiseDataError(DataGridViewDataErrorEventArgs)

DataError 이벤트를 발생시킵니다.

(다음에서 상속됨 DataGridViewElement)
RaiseMouseWheel(MouseEventArgs)

MouseWheel 이벤트를 발생시킵니다.

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

열을 설명하는 문자열을 가져옵니다.

이벤트

Disposed

DataGridViewColumn이 삭제될 때 발생합니다.

적용 대상

제품 버전
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9

추가 정보