DataGridViewColumn Class

 

Represents a column in a DataGridView control.

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


public ref class DataGridViewColumn : DataGridViewBand, IComponent, 
	IDisposable

NameDescription
System_CAPS_pubmethodDataGridViewColumn()

Initializes a new instance of the DataGridViewColumn class to the default state.

System_CAPS_pubmethodDataGridViewColumn(DataGridViewCell^)

Initializes a new instance of the DataGridViewColumn class using an existing DataGridViewCell as a template.

NameDescription
System_CAPS_pubpropertyAutoSizeMode

Gets or sets the mode by which the column automatically adjusts its width.

System_CAPS_pubpropertyCellTemplate

Gets or sets the template used to create new cells.

System_CAPS_pubpropertyCellType

Gets the run-time type of the cell template.

System_CAPS_pubpropertyContextMenuStrip

Gets or sets the shortcut menu for the column.(Overrides DataGridViewBand::ContextMenuStrip.)

System_CAPS_pubpropertyDataGridView

Gets the DataGridView control associated with this element.(Inherited from DataGridViewElement.)

System_CAPS_pubpropertyDataPropertyName

Gets or sets the name of the data source property or database column to which the DataGridViewColumn is bound.

System_CAPS_pubpropertyDefaultCellStyle

Gets or sets the column's default cell style.(Overrides DataGridViewBand::DefaultCellStyle.)

System_CAPS_pubpropertyDefaultHeaderCellType

Gets or sets the run-time type of the default header cell.(Inherited from DataGridViewBand.)

System_CAPS_pubpropertyDisplayed

Gets a value indicating whether the band is currently displayed onscreen. (Inherited from DataGridViewBand.)

System_CAPS_pubpropertyDisplayIndex

Gets or sets the display order of the column relative to the currently displayed columns.

System_CAPS_pubpropertyDividerWidth

Gets or sets the width, in pixels, of the column divider.

System_CAPS_pubpropertyFillWeight

Gets or sets a value that represents the width of the column when it is in fill mode relative to the widths of other fill-mode columns in the control.

System_CAPS_pubpropertyFrozen

Gets or sets a value indicating whether a column will move when a user scrolls the DataGridView control horizontally.(Overrides DataGridViewBand::Frozen.)

System_CAPS_pubpropertyHasDefaultCellStyle

Gets a value indicating whether the DefaultCellStyle property has been set. (Inherited from DataGridViewBand.)

System_CAPS_pubpropertyHeaderCell

Gets or sets the DataGridViewColumnHeaderCell that represents the column header.

System_CAPS_protpropertyHeaderCellCore

Gets or sets the header cell of the DataGridViewBand.(Inherited from DataGridViewBand.)

System_CAPS_pubpropertyHeaderText

Gets or sets the caption text on the column's header cell.

System_CAPS_pubpropertyIndex

Gets the relative position of the band within the DataGridView control.(Inherited from DataGridViewBand.)

System_CAPS_pubpropertyInheritedAutoSizeMode

Gets the sizing mode in effect for the column.

System_CAPS_pubpropertyInheritedStyle

Gets the cell style currently applied to the column.(Overrides DataGridViewBand::InheritedStyle.)

System_CAPS_pubpropertyIsDataBound

Gets a value indicating whether the column is bound to a data source.

System_CAPS_protpropertyIsRow

Gets a value indicating whether the band represents a row.(Inherited from DataGridViewBand.)

System_CAPS_pubpropertyMinimumWidth

Gets or sets the minimum width, in pixels, of the column.

System_CAPS_pubpropertyName

Gets or sets the name of the column.

System_CAPS_pubpropertyReadOnly

Gets or sets a value indicating whether the user can edit the column's cells.(Overrides DataGridViewBand::ReadOnly.)

System_CAPS_pubpropertyResizable

Gets or sets a value indicating whether the column is resizable.(Overrides DataGridViewBand::Resizable.)

System_CAPS_pubpropertySelected

Gets or sets a value indicating whether the band is in a selected user interface (UI) state.(Inherited from DataGridViewBand.)

System_CAPS_pubpropertySite

This API supports the product infrastructure and is not intended to be used directly from your code. Gets or sets the site of the column.

System_CAPS_pubpropertySortMode

Gets or sets the sort mode for the column.

System_CAPS_pubpropertyState

Gets the user interface (UI) state of the element.(Inherited from DataGridViewElement.)

System_CAPS_pubpropertyTag

Gets or sets the object that contains data to associate with the band.(Inherited from DataGridViewBand.)

System_CAPS_pubpropertyToolTipText

Gets or sets the text used for ToolTips.

System_CAPS_pubpropertyValueType

Gets or sets the data type of the values in the column's cells.

System_CAPS_pubpropertyVisible

Gets or sets a value indicating whether the column is visible.(Overrides DataGridViewBand::Visible.)

System_CAPS_pubpropertyWidth

Gets or sets the current width of the column.

NameDescription
System_CAPS_pubmethodClone()

Creates an exact copy of this band.(Overrides DataGridViewBand::Clone().)

System_CAPS_pubmethodDispose()

Releases all resources used by the DataGridViewBand. (Inherited from DataGridViewBand.)

System_CAPS_protmethodDispose(Boolean)

Releases the unmanaged resources used by the DataGridViewBand and optionally releases the managed resources.(Overrides DataGridViewBand::Dispose(Boolean).)

System_CAPS_pubmethodEquals(Object^)

Determines whether the specified object is equal to the current object.(Inherited from Object.)

System_CAPS_protmethodFinalize()

Releases the resources associated with the band.(Inherited from DataGridViewBand.)

System_CAPS_pubmethodGetHashCode()

Serves as the default hash function. (Inherited from Object.)

System_CAPS_pubmethodGetPreferredWidth(DataGridViewAutoSizeColumnMode, Boolean)

Calculates the ideal width of the column based on the specified criteria.

System_CAPS_pubmethodGetType()

Gets the Type of the current instance.(Inherited from Object.)

System_CAPS_protmethodMemberwiseClone()

Creates a shallow copy of the current Object.(Inherited from Object.)

System_CAPS_protmethodOnDataGridViewChanged()

Called when the band is associated with a different DataGridView.(Inherited from DataGridViewBand.)

System_CAPS_protmethodRaiseCellClick(DataGridViewCellEventArgs^)

Raises the DataGridView::CellClick event. (Inherited from DataGridViewElement.)

System_CAPS_protmethodRaiseCellContentClick(DataGridViewCellEventArgs^)

Raises the DataGridView::CellContentClick event. (Inherited from DataGridViewElement.)

System_CAPS_protmethodRaiseCellContentDoubleClick(DataGridViewCellEventArgs^)

Raises the DataGridView::CellContentDoubleClick event. (Inherited from DataGridViewElement.)

System_CAPS_protmethodRaiseCellValueChanged(DataGridViewCellEventArgs^)

Raises the DataGridView::CellValueChanged event. (Inherited from DataGridViewElement.)

System_CAPS_protmethodRaiseDataError(DataGridViewDataErrorEventArgs^)

Raises the DataGridView::DataError event. (Inherited from DataGridViewElement.)

System_CAPS_protmethodRaiseMouseWheel(MouseEventArgs^)

Raises the Control::MouseWheel event. (Inherited from DataGridViewElement.)

System_CAPS_pubmethodToString()

Gets a string that describes the column.(Overrides DataGridViewBand::ToString().)

NameDescription
System_CAPS_pubeventDisposed

Occurs when the DataGridViewColumn is disposed.

The DataGridViewColumn class represents a logical column in a DataGridView control. You can retrieve columns through the Columns collection of the control.

Unlike a DataGridViewRow, which contains the actual collection of cells in a DataGridView, 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 DataGridViewColumn typically initialize the CellTemplate property to a new instance of a related type derived from the 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.

Notes to Inheritors:

When you derive from DataGridViewColumn and add new properties to the derived class, be sure to override the Clone method to copy the new properties during cloning operations. You should also call the base class's 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 DataGridView and a set of buttons. Each button label describes an operation related to a DataGridViewColumn property, such as swapping the first and last column (using the DisplayIndex property) or changing the text of a column header (using the HeaderText property). Clicking a button changes the associated property of the DataGridViewColumn.

#using <System.Drawing.dll>
#using <System.dll>
#using <system.windows.forms.dll>

using namespace System;
using namespace System::Windows::Forms;
using namespace System::Drawing;
using namespace System::Collections;
public ref class DataGridViewColumnDemo: public Form
{
private:

#pragma region S "set up form" 

public:
   DataGridViewColumnDemo()
   {
      Button1 = gcnew Button;
      Button2 = gcnew Button;
      Button3 = gcnew Button;
      Button4 = gcnew Button;
      Button5 = gcnew Button;
      Button6 = gcnew Button;
      Button7 = gcnew Button;
      Button8 = gcnew Button;
      Button9 = gcnew Button;
      Button10 = gcnew Button;
      FlowLayoutPanel1 = gcnew FlowLayoutPanel;
      thirdColumnHeader = L"Main Ingredients";
      boringMeatloaf = L"ground beef";
      boringMeatloafRanking = L"*";
      toolStripItem1 = gcnew ToolStripMenuItem;
      InitializeComponent();
      AddButton( Button1, L"Reset", gcnew EventHandler( this, &DataGridViewColumnDemo::ResetToDisorder ) );
      AddButton( Button2, L"Change Column 3 Header", gcnew EventHandler( this, &DataGridViewColumnDemo::ChangeColumn3Header ) );
      AddButton( Button3, L"Change Meatloaf Recipe", gcnew EventHandler( this, &DataGridViewColumnDemo::ChangeMeatloafRecipe ) );
      AddAdditionalButtons();
      InitializeDataGridView();
   }

   DataGridView^ dataGridView;
   Button^ Button1;
   Button^ Button2;
   Button^ Button3;
   Button^ Button4;
   Button^ Button5;
   Button^ Button6;
   Button^ Button7;
   Button^ Button8;
   Button^ Button9;
   Button^ Button10;
   FlowLayoutPanel^ FlowLayoutPanel1;

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


#pragma endregion 
#pragma region S " set up DataGridView " 
   String^ thirdColumnHeader;
   String^ boringMeatloaf;
   String^ boringMeatloafRanking;
   bool boringRecipe;
   bool shortMode;
   void InitializeDataGridView()
   {
      dataGridView = gcnew System::Windows::Forms::DataGridView;
      Controls->Add( dataGridView );
      dataGridView->Size = System::Drawing::Size( 300, 200 );

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

      // Set the column header style.
      DataGridViewCellStyle^ columnHeaderStyle = gcnew DataGridViewCellStyle;
      columnHeaderStyle->BackColor = Color::Aqua;
      columnHeaderStyle->Font = gcnew System::Drawing::Font( L"Verdana",10,FontStyle::Bold );
      dataGridView->ColumnHeadersDefaultCellStyle = columnHeaderStyle;

      // Set the column header names.
      dataGridView->Columns[ 0 ]->Name = L"Recipe";
      dataGridView->Columns[ 1 ]->Name = L"Category";
      dataGridView->Columns[ 2 ]->Name = thirdColumnHeader;
      dataGridView->Columns[ 3 ]->Name = L"Rating";
      criteriaLabel = L"Column 3 sizing criteria: ";
      PostColumnCreation();

      // Populate the rows.
      array<String^>^row1 = gcnew array<String^>{
         L"Meatloaf",L"Main Dish",boringMeatloaf,boringMeatloafRanking
      };
      array<String^>^row2 = gcnew array<String^>{
         L"Key Lime Pie",L"Dessert",L"lime juice, evaporated milk",L"****"
      };
      array<String^>^row3 = gcnew array<String^>{
         L"Orange-Salsa Pork Chops",L"Main Dish",L"pork chops, salsa, orange juice",L"****"
      };
      array<String^>^row4 = gcnew array<String^>{
         L"Black Bean and Rice Salad",L"Salad",L"black beans, brown rice",L"****"
      };
      array<String^>^row5 = gcnew array<String^>{
         L"Chocolate Cheesecake",L"Dessert",L"cream cheese",L"***"
      };
      array<String^>^row6 = gcnew array<String^>{
         L"Black Bean Dip",L"Appetizer",L"black beans, sour cream",L"***"
      };
      array<Object^>^rows = gcnew array<Object^>{
         row1,row2,row3,row4,row5,row6
      };
      System::Collections::IEnumerator^ myEnum = rows->GetEnumerator();
      while ( myEnum->MoveNext() )
      {
         array<String^>^rowArray = safe_cast<array<String^>^>(myEnum->Current);
         dataGridView->Rows->Add( rowArray );
      }

      shortMode = false;
      boringRecipe = true;
   }

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

   void ResetToDisorder( Object^ /*sender*/, System::EventArgs^ /*e*/ )
   {
      Controls->Remove( dataGridView );
      dataGridView->~DataGridView();
      InitializeDataGridView();
   }

   void ChangeColumn3Header( Object^ /*sender*/, System::EventArgs^ /*e*/ )
   {
      Toggle(  &shortMode );
      if ( shortMode )
      {
         dataGridView->Columns[ 2 ]->HeaderText = L"S";
      }
      else
      {
         dataGridView->Columns[ 2 ]->HeaderText = thirdColumnHeader;
      }
   }

   void Toggle( interior_ptr<Boolean> toggleThis )
   {
       *toggleThis =  ! *toggleThis;
   }

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

   void SetMeatloaf( String^ recipe, String^ rating )
   {
      dataGridView->Rows[ 0 ]->Cells[ 2 ]->Value = recipe;
      dataGridView->Rows[ 0 ]->Cells[ 3 ]->Value = rating;
   }


#pragma endregion 

public:
   static void Main()
   {
      Application::Run( gcnew DataGridViewColumnDemo );
   }


#pragma region S " demonstration code " 

private:
   void PostColumnCreation()
   {
      AddContextLabel();
      AddCriteriaLabel();
      CustomizeCellsInThirdColumn();
      AddContextMenu();
      SetDefaultCellInFirstColumn();
      ToolTips();
      dataGridView->CellMouseEnter += gcnew DataGridViewCellEventHandler( this, &DataGridViewColumnDemo::dataGridView_CellMouseEnter );
      dataGridView->AutoSizeColumnModeChanged += gcnew DataGridViewAutoSizeColumnModeEventHandler( this, &DataGridViewColumnDemo::dataGridView_AutoSizeColumnModeChanged );
   }

   String^ criteriaLabel;
   void AddCriteriaLabel()
   {
      AddLabelToPanelIfNotAlreadyThere( criteriaLabel, String::Concat( criteriaLabel, dataGridView->Columns[ 2 ]->AutoSizeMode, L"." ) );
   }

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

   void AddLabelToPanelIfNotAlreadyThere( String^ labelName, String^ labelText )
   {
      Label^ label;
      if ( FlowLayoutPanel1->Controls[ labelName ] == nullptr )
      {
         label = gcnew Label;
         label->AutoSize = true;
         label->Name = labelName;
         label->BackColor = Color::Bisque;
         FlowLayoutPanel1->Controls->Add( label );
      }
      else
      {
         label = dynamic_cast<Label^>(FlowLayoutPanel1->Controls[ labelName ]);
      }

      label->Text = labelText;
   }


   void CustomizeCellsInThirdColumn()
   {
      int thirdColumn = 2;
      DataGridViewColumn^ column = dataGridView->Columns[ thirdColumn ];
      DataGridViewCell^ cell = gcnew DataGridViewTextBoxCell;
      cell->Style->BackColor = Color::Wheat;
      column->CellTemplate = cell;
   }


   ToolStripMenuItem^ toolStripItem1;
   void AddContextMenu()
   {
      toolStripItem1->Text = L"Redden";
      toolStripItem1->Click += gcnew EventHandler( this, &DataGridViewColumnDemo::toolStripItem1_Click );
      System::Windows::Forms::ContextMenuStrip^ strip = gcnew System::Windows::Forms::ContextMenuStrip;
      IEnumerator^ myEnum = dataGridView->Columns->GetEnumerator();
      while ( myEnum->MoveNext() )
      {
         DataGridViewColumn^ column = safe_cast<DataGridViewColumn^>(myEnum->Current);
         column->ContextMenuStrip = strip;
         column->ContextMenuStrip->Items->Add( toolStripItem1 );
      }
   }

   DataGridViewCellEventArgs^ mouseLocation;

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


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


   void SetDefaultCellInFirstColumn()
   {
      DataGridViewColumn^ firstColumn = dataGridView->Columns[ 0 ];
      DataGridViewCellStyle^ cellStyle = gcnew DataGridViewCellStyle;
      cellStyle->BackColor = Color::Thistle;
      firstColumn->DefaultCellStyle = cellStyle;
   }


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


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

   void AdjustDataGridViewSizing()
   {
      dataGridView->ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode::AutoSize;
   }


   //Set the minimum width.
   void Button4_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
   {
      DataGridViewColumn^ column = dataGridView->Columns[ 1 ];
      column->MinimumWidth = 40;
   }


   // Set the width.
   void Button5_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
   {
      DataGridViewColumn^ column = dataGridView->Columns[ 0 ];
      column->Width = 60;
   }


   // AutoSize the third column.
   void Button6_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
   {
      DataGridViewColumn^ column = dataGridView->Columns[ 2 ];
      column->AutoSizeMode = DataGridViewAutoSizeColumnMode::DisplayedCells;
   }


   // Set the vertical edge.
   void Button7_Click( Object^ /*sender*/, System::EventArgs^ /*e*/ )
   {
      int thirdColumn = 2;

      //        int edgeThickness = 5;
      DataGridViewColumn^ column = dataGridView->Columns[ thirdColumn ];
      column->DividerWidth = 10;
   }


   // Style and number columns.
   void Button8_Click( Object^ /*sender*/, EventArgs^ /*args*/ )
   {
      DataGridViewCellStyle^ style = gcnew DataGridViewCellStyle;
      style->Alignment = DataGridViewContentAlignment::MiddleCenter;
      style->ForeColor = Color::IndianRed;
      style->BackColor = Color::Ivory;
      IEnumerator^ myEnum1 = dataGridView->Columns->GetEnumerator();
      while ( myEnum1->MoveNext() )
      {
         DataGridViewColumn^ column = safe_cast<DataGridViewColumn^>(myEnum1->Current);
         column->HeaderCell->Value = column->Index.ToString();
         column->HeaderCell->Style = style;
      }
   }


   // Change the text in the column header.
   void Button9_Click( Object^ /*sender*/, EventArgs^ /*args*/ )
   {
      IEnumerator^ myEnum2 = dataGridView->Columns->GetEnumerator();
      while ( myEnum2->MoveNext() )
      {
         DataGridViewColumn^ column = safe_cast<DataGridViewColumn^>(myEnum2->Current);
         column->HeaderText = String::Concat( L"Column ", column->Index.ToString() );
      }
   }


   // Swap the last column with the first.
   void Button10_Click( Object^ /*sender*/, EventArgs^ /*args*/ )
   {
      DataGridViewColumnCollection^ columnCollection = dataGridView->Columns;
      DataGridViewColumn^ firstDisplayedColumn = columnCollection->GetFirstColumn( DataGridViewElementStates::Visible );
      DataGridViewColumn^ lastDisplayedColumn = columnCollection->GetLastColumn( DataGridViewElementStates::Visible, DataGridViewElementStates::None );
      int firstColumn_sIndex = firstDisplayedColumn->DisplayIndex;
      firstDisplayedColumn->DisplayIndex = lastDisplayedColumn->DisplayIndex;
      lastDisplayedColumn->DisplayIndex = firstColumn_sIndex;
   }


   // Updated the criteria label.
   void dataGridView_AutoSizeColumnModeChanged( Object^ /*sender*/, DataGridViewAutoSizeColumnModeEventArgs^ args )
   {
      args->Column->DataGridView->Parent->Controls[ L"flowlayoutpanel" ]->Controls[ criteriaLabel ]->Text = String::Concat( criteriaLabel, args->Column->AutoSizeMode );
   }
#pragma endregion 

};

int main()
{
   DataGridViewColumnDemo::Main();
}

.NET Framework
Available since 2.0

Any public static ( Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Return to top
Show: