Este artigo foi traduzido por máquina. Para visualizar o arquivo em inglês, marque a caixa de seleção Inglês. Você também pode exibir o texto Em inglês em uma janela pop-up, movendo o ponteiro do mouse sobre o texto.
Tradução
Inglês

Classe DataGridViewColumn

 

Representa uma coluna em um controle DataGridView.

Namespace:   System.Windows.Forms
Assembly:  System.Windows.Forms (em System.Windows.Forms.dll)


public class DataGridViewColumn : DataGridViewBand, IComponent, 
	IDisposable

NomeDescrição
System_CAPS_pubmethodDataGridViewColumn()

Inicializa uma nova instância da classe DataGridViewColumn com o estado padrão.

System_CAPS_pubmethodDataGridViewColumn(DataGridViewCell)

Inicializa uma nova instância da classe DataGridViewColumn usando um DataGridViewCell existente como modelo.

NomeDescrição
System_CAPS_pubpropertyAutoSizeMode

Obtém ou define o modo pelo qual a coluna ajusta a largura automaticamente.

System_CAPS_pubpropertyCellTemplate

Obtém ou define o modelo usado para criar novas células.

System_CAPS_pubpropertyCellType

Obtém o tipo de tempo de execução do modelo de célula.

System_CAPS_pubpropertyContextMenuStrip

Obtém ou define o menu de atalho da coluna.(Substitui o DataGridViewBand.ContextMenuStrip.)

System_CAPS_pubpropertyDataGridView

Obtém o controle de DataGridView associado a esse elemento.(Herdado de DataGridViewElement.)

System_CAPS_pubpropertyDataPropertyName

Obtém ou define o nome da propriedade da fonte de dados ou da coluna de banco de dados à qual DataGridViewColumn está associado.

System_CAPS_pubpropertyDefaultCellStyle

Obtém ou define o estilo da célula padrão da coluna.(Substitui o DataGridViewBand.DefaultCellStyle.)

System_CAPS_pubpropertyDefaultHeaderCellType

Obtém ou define o tipo de tempo de execução da célula de cabeçalho padrão.(Herdado de DataGridViewBand.)

System_CAPS_pubpropertyDisplayed

Obtém um valor que indica se a banda é exibida na tela no momento.(Herdado de DataGridViewBand.)

System_CAPS_pubpropertyDisplayIndex

Obtém ou define a ordem de exibição da coluna em relação às colunas exibidas no momento.

System_CAPS_pubpropertyDividerWidth

Obtém ou define a largura mínima, em pixels, do divisor de coluna.

System_CAPS_pubpropertyFillWeight

Obtém ou define um valor que representa a largura da coluna quando ela está no modo de preenchimento em relação à largura das outras colunas de modo de preenchimento no controle.

System_CAPS_pubpropertyFrozen

Obtém ou define um valor que indica se uma coluna será movida quando um usuário rolar o controle DataGridView horizontalmente.(Substitui o DataGridViewBand.Frozen.)

System_CAPS_pubpropertyHasDefaultCellStyle

Obtém um valor que indica se o DefaultCellStyle propriedade foi definida.(Herdado de DataGridViewBand.)

System_CAPS_pubpropertyHeaderCell

Obtém ou define o DataGridViewColumnHeaderCell que representa o cabeçalho da coluna.

System_CAPS_protpropertyHeaderCellCore

Obtém ou define a célula de cabeçalho de DataGridViewBand.(Herdado de DataGridViewBand.)

System_CAPS_pubpropertyHeaderText

Obtém ou define o texto de legenda na célula do cabeçalho da coluna.

System_CAPS_pubpropertyIndex

Obtém a posição relativa da faixa dentro do controle DataGridView.(Herdado de DataGridViewBand.)

System_CAPS_pubpropertyInheritedAutoSizeMode

Obtém o modo de redimensionamento em vigor para a coluna.

System_CAPS_pubpropertyInheritedStyle

Obtém o estilo atualmente aplicado à coluna da célula.(Substitui o DataGridViewBand.InheritedStyle.)

System_CAPS_pubpropertyIsDataBound

Obtém um valor que indica se a coluna está associada a uma fonte de dados.

System_CAPS_protpropertyIsRow

Obtém um valor que indica se a banda representa uma linha.(Herdado de DataGridViewBand.)

System_CAPS_pubpropertyMinimumWidth

Obtém ou define a largura mínima, em pixels, da coluna.

System_CAPS_pubpropertyName

Obtém ou define o nome da coluna.

System_CAPS_pubpropertyReadOnly

Obtém ou define um valor que indica se o usuário pode editar as células da coluna.(Substitui o DataGridViewBand.ReadOnly.)

System_CAPS_pubpropertyResizable

Obtém ou define um valor que indica se a coluna é redimensionável.(Substitui o DataGridViewBand.Resizable.)

System_CAPS_pubpropertySelected

Obtém ou define um valor que indica se a banda está em um estado de interface do usuário selecionado.(Herdado de DataGridViewBand.)

System_CAPS_pubpropertySite

Esta API dá suporte à infraestrutura produto e não se destina a ser usada diretamente do seu código. Obtém ou define o local da coluna.

System_CAPS_pubpropertySortMode

Obtém ou define o modo de classificação da coluna.

System_CAPS_pubpropertyState

Obtém o estado da UI (interface do usuário) do elemento.(Herdado de DataGridViewElement.)

System_CAPS_pubpropertyTag

Obtém ou define o objeto que contém os dados associados à banda.(Herdado de DataGridViewBand.)

System_CAPS_pubpropertyToolTipText

Obtém ou define o texto usado para Dicas de Ferramentas.

System_CAPS_pubpropertyValueType

Obtém ou define o tipo de dados dos valores nas células da coluna.

System_CAPS_pubpropertyVisible

Obtém ou define um valor que indica se a coluna está visível.(Substitui o DataGridViewBand.Visible.)

System_CAPS_pubpropertyWidth

Obtém ou define a largura atual da coluna.

NomeDescrição
System_CAPS_pubmethodClone()

Cria uma cópia exata dessa faixa.(Substitui o DataGridViewBand.Clone().)

System_CAPS_pubmethodDispose()

Libera todos os recursos usados pelo DataGridViewBand.(Herdado de DataGridViewBand.)

System_CAPS_protmethodDispose(Boolean)

Libera os recursos não gerenciados usados pelo DataGridViewBand e opcionalmente libera os recursos gerenciados.(Substitui o DataGridViewBand.Dispose(Boolean).)

System_CAPS_pubmethodEquals(Object)

Verifica se o objeto especificado é igual ao objeto atual. (Herdado de Object.)

System_CAPS_protmethodFinalize()

Libera os recursos associados com a faixa.(Herdado de DataGridViewBand.)

System_CAPS_pubmethodGetHashCode()

Serve como a função de hash padrão.(Herdado de Object.)

System_CAPS_pubmethodGetPreferredWidth(DataGridViewAutoSizeColumnMode, Boolean)

Calcula a largura ideal da coluna com base nos critérios especificados.

System_CAPS_pubmethodGetType()

Obtém o Type da instância atual.(Herdado de Object.)

System_CAPS_protmethodMemberwiseClone()

Cria uma cópia superficial do Object atual.(Herdado de Object.)

System_CAPS_protmethodOnDataGridViewChanged()

Chamado quando a banda está associada a outro DataGridView.(Herdado de DataGridViewBand.)

System_CAPS_protmethodRaiseCellClick(DataGridViewCellEventArgs)

Gera o DataGridView.CellClick evento.(Herdado de DataGridViewElement.)

System_CAPS_protmethodRaiseCellContentClick(DataGridViewCellEventArgs)
System_CAPS_protmethodRaiseCellContentDoubleClick(DataGridViewCellEventArgs)
System_CAPS_protmethodRaiseCellValueChanged(DataGridViewCellEventArgs)
System_CAPS_protmethodRaiseDataError(DataGridViewDataErrorEventArgs)

Gera o DataGridView.DataError evento.(Herdado de DataGridViewElement.)

System_CAPS_protmethodRaiseMouseWheel(MouseEventArgs)

Gera o Control.MouseWheel evento.(Herdado de DataGridViewElement.)

System_CAPS_pubmethodToString()

Obtém uma cadeia de caracteres que descreve a coluna.(Substitui o DataGridViewBand.ToString().)

NomeDescrição
System_CAPS_pubeventDisposed

Ocorre quando o DataGridViewColumn é descartado.

The T:System.Windows.Forms.DataGridViewColumn class represents a logical column in a T:System.Windows.Forms.DataGridView control. You can retrieve columns through the P:System.Windows.Forms.DataGridView.Columns collection of the control.

Unlike a T:System.Windows.Forms.DataGridViewRow, which contains the actual collection of cells in a T:System.Windows.Forms.DataGridView, T:System.Windows.Forms.DataGridViewColumn is used mainly to adjust the appearance and behavior of the column user interface (UI), such as column width and cell style. For more information about cell styles, see Cell Styles in the Windows Forms DataGridView Control.

Types that derive from T:System.Windows.Forms.DataGridViewColumn typically initialize the P:System.Windows.Forms.DataGridViewColumn.CellTemplate property to a new instance of a related type derived from the T:System.Windows.Forms.DataGridViewCell class. Any column properties that relate to the appearance or behavior of individual cells are wrappers for the corresponding properties of the template cell. Changing one of these properties on the column automatically changes the value on the cell template and on all cells in the column. To override the specified value for individual cells, set the cell values after you set the column value.

Observações para os Herdeiros:

When you derive from T:System.Windows.Forms.DataGridViewColumn and add new properties to the derived class, be sure to override the M:System.Windows.Forms.DataGridViewColumn.Clone method to copy the new properties during cloning operations. You should also call the base class's M:System.Windows.Forms.DataGridViewColumn.Clone method so that the properties of the base class are copied to the new cell.

The following code example creates a Windows Form with a T:System.Windows.Forms.DataGridView and a set of buttons. Each button label describes an operation related to a T:System.Windows.Forms.DataGridViewColumn property, such as swapping the first and last column (using the P:System.Windows.Forms.DataGridViewColumn.DisplayIndex property) or changing the text of a column header (using the P:System.Windows.Forms.DataGridViewColumn.HeaderText property). Clicking a button changes the associated property of the T:System.Windows.Forms.DataGridViewColumn.

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());
    }

}

.NET Framework
Disponível desde 2.0

Quaisquer membros estáticos públicos ( Compartilhado no Visual Basic) desse tipo são thread-safe. Não há garantia de que qualquer membro de instância seja thread-safe.

Retornar ao início
Mostrar: