DataGridViewColumn 类

定义

表示 DataGridView 控件中的列。

C#
[System.ComponentModel.TypeConverter(typeof(System.Windows.Forms.DataGridViewColumnConverter))]
public class DataGridViewColumn : System.Windows.Forms.DataGridViewBand, IDisposable, System.ComponentModel.IComponent
继承
派生
属性
实现

示例

下面的代码示例创建一个包含 DataGridView 和一组按钮的 Windows 窗体。 每个按钮标签描述与属性相关的 DataGridViewColumn 操作,例如使用 DisplayIndex 属性) 交换第一列和最后一列 (或使用属性) (HeaderText 更改列标题的文本。 单击按钮会更改 的 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与 (它包含 中DataGridView单元格的实际集合)不同,DataGridViewColumn主要用于调整列用户界面的外观和行为, (UI) ,如列宽和单元格样式。 有关单元格样式的详细信息,请参阅 Windows 窗体 DataGridView 控件中的单元格样式

派生自 DataGridViewColumn 的类型通常会将 CellTemplate 属性初始化为派生自 DataGridViewCell 类的相关类型的新实例。 与单个单元格的外观或行为相关的任何列属性都是模板单元格的相应属性的包装器。 更改列上的其中一个属性会自动更改单元格模板和列中的所有单元格上的值。 若要替代单个单元格的指定值,请在设置列值后设置单元格值。

继承者说明

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

获取或设置一个值,该值指示带区是否为被选定。

(继承自 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, 10

另请参阅