DataGridViewColumn 类

定义

表示 DataGridView 控件中的列。Represents a column in a DataGridView control.

public ref class DataGridViewColumn : System::Windows::Forms::DataGridViewBand, IDisposable, System::ComponentModel::IComponent
[System.ComponentModel.TypeConverter(typeof(System.Windows.Forms.DataGridViewColumnConverter))]
public class DataGridViewColumn : System.Windows.Forms.DataGridViewBand, IDisposable, System.ComponentModel.IComponent
type DataGridViewColumn = class
    inherit DataGridViewBand
    interface IComponent
    interface IDisposable
Public Class DataGridViewColumn
Inherits DataGridViewBand
Implements IComponent, IDisposable
继承
派生
属性
实现

示例

下面的代码示例创建一个 Windows 窗体, DataGridView其中包含一组按钮。The following code example creates a Windows Form with a DataGridView and a set of buttons. 每个按钮标签都描述与DataGridViewColumn属性相关的操作,如交换第一列和最后一列( DisplayIndex使用属性)或更改HeaderText列标题的文本(使用属性)。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). 单击按钮将更改的DataGridViewColumn关联属性。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();
}

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

}
Imports System.Windows.Forms
Imports System.Drawing

Public Class DataGridViewColumnDemo
    Inherits Form

#Region "set up form"
    Public Sub New()
        InitializeComponent()

        AddButton(Button1, "Reset")
        AddButton(Button2, "Change Column 3 Header")
        AddButton(Button3, "Change Meatloaf Recipe")
        AddAdditionalButtons()
    End Sub

    Friend WithEvents dataGridView As DataGridView
    Friend WithEvents Button1 As Button = New Button()
    Friend WithEvents Button2 As Button = New Button()
    Friend WithEvents Button3 As Button = New Button()
    Friend WithEvents Button4 As Button = New Button()
    Friend WithEvents Button5 As Button = New Button()
    Friend WithEvents Button6 As Button = New Button()
    Friend WithEvents Button7 As Button = New Button()
    Friend WithEvents Button8 As Button = New Button()
    Friend WithEvents Button9 As Button = New Button()
    Friend WithEvents Button10 As Button = New Button()
    Friend WithEvents FlowLayoutPanel1 As FlowLayoutPanel _
        = New FlowLayoutPanel()

    Private Sub 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(FlowLayoutPanel1)
        Text = Me.GetType.Name
        AutoSize = True
    End Sub
#End Region

#Region "set up DataGridView"
    Private thirdColumnHeader As String = "Main Ingredients"
    Private boringMeatloaf As String = "ground beef"
    Private boringMeatloafRanking As String = "*"
    Private boringRecipe As Boolean
    Private shortMode As Boolean

    Private Sub InitializeDataGridView(ByVal ignored As Object, _
    ByVal ignoredToo As EventArgs) Handles Me.Load

        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.
        Dim columnHeaderStyle As 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.
        Dim row1 As String() = New String() _
            {"Meatloaf", "Main Dish", boringMeatloaf, _
            boringMeatloafRanking}
        Dim row2 As String() = New String() _
            {"Key Lime Pie", "Dessert", _
            "lime juice, evaporated milk", _
            "****"}
        Dim row3 As String() = New String() _
            {"Orange-Salsa Pork Chops", "Main Dish", _
            "pork chops, salsa, orange juice", "****"}
        Dim row4 As String() = New String() _
            {"Black Bean and Rice Salad", "Salad", _
            "black beans, brown rice", _
            "****"}
        Dim row5 As String() = New String() _
            {"Chocolate Cheesecake", "Dessert", "cream cheese", _
            "***"}
        Dim row6 As String() = New String() _
            {"Black Bean Dip", "Appetizer", _
            "black beans, sour cream", _
                "***"}
        Dim rows As Object() = New Object() {row1, row2, _
            row3, row4, row5, row6}

        Dim rowArray As String()
        For Each rowArray In rows
            dataGridView.Rows.Add(rowArray)
        Next

        shortMode = False
        boringRecipe = True
    End Sub

    Private Sub AddButton(ByVal button As Button, _
        ByVal buttonLabel As String)

        FlowLayoutPanel1.Controls.Add(button)
        button.TabIndex = FlowLayoutPanel1.Controls.Count
        button.Text = buttonLabel
        button.AutoSize = True
    End Sub

    Private Sub ResetToDisorder(ByVal sender As Object, _
        ByVal e As System.EventArgs) _
        Handles Button1.Click
        Controls.Remove(dataGridview)
        dataGridView.Dispose()
        InitializeDataGridView(Nothing, Nothing)
    End Sub

    Private Sub ChangeColumn3Header(ByVal sender As Object, _
        ByVal e As System.EventArgs) _
        Handles Button2.Click

        Toggle(shortMode)
        If shortMode Then dataGridView.Columns(2).HeaderText = _
            "S" _
            Else dataGridView.Columns(2).HeaderText = _
                thirdColumnHeader
    End Sub

    Private Shared Sub Toggle(ByRef toggleThis As Boolean)
        toggleThis = Not toggleThis
    End Sub

    Private Sub ChangeMeatloafRecipe(ByVal sender As Object, _
        ByVal e As System.EventArgs) _
        Handles Button3.Click

        Toggle(boringRecipe)
        If boringRecipe Then
            SetMeatloaf(boringMeatloaf, boringMeatloafRanking)
        Else
            Dim greatMeatloafRecipe As String = "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, "***")
        End If
    End Sub

    Private Sub SetMeatloaf(ByVal recipe As String, _
        ByVal rating As String)

        dataGridView.Rows(0).Cells(2).Value = recipe
        dataGridView.Rows(0).Cells(3).Value = rating
    End Sub
#End Region

#Region "demonstration code"
    Private Sub PostColumnCreation()
        AddContextLabel()
        AddCriteriaLabel()
        CustomizeCellsInThirdColumn()
        AddContextMenu()
        SetDefaultCellInFirstColumn()
        ToolTips()
    End Sub

    Private criteriaLabel As String = "Column 3 sizing criteria: "
    Private Sub AddCriteriaLabel()
        AddLabelToPanelIfNotAlreadyThere(criteriaLabel, _
            criteriaLabel & _
            dataGridView.Columns(2).AutoSizeMode.ToString() _
            & ".")
    End Sub

    Private Sub AddContextLabel()
        Dim labelName As String = "label"
        AddLabelToPanelIfNotAlreadyThere(labelName, _
            "Use shortcut menu to change cell color.")
    End Sub

    Private Sub AddLabelToPanelIfNotAlreadyThere( _
    ByVal labelName As String, _
    ByVal labelText As String)

        Dim label As Label
        If FlowLayoutPanel1.Controls(labelName) Is Nothing Then
            label = New Label()
            label.AutoSize = True
            label.Name = labelName
            label.BackColor = Color.Bisque
            FlowLayoutPanel1.Controls.Add(label)
        Else
            label = CType(FlowLayoutPanel1.Controls(labelName), Label)
        End If
        label.Text = labelText
    End Sub

    Private Sub CustomizeCellsInThirdColumn()

        Dim thirdColumn As Integer = 2
        Dim column As DataGridViewColumn = _
            dataGridView.Columns(thirdColumn)
        Dim cell As DataGridViewCell = _
            New DataGridViewTextBoxCell()

        cell.Style.BackColor = Color.Wheat
        column.CellTemplate = cell
    End Sub

    WithEvents toolStripItem1 As New ToolStripMenuItem()

    Private Sub AddContextMenu()
        toolStripItem1.Text = "Redden"
        Dim strip As New ContextMenuStrip()
        For Each column As DataGridViewColumn _
            In dataGridView.Columns()

            column.ContextMenuStrip = strip
            column.ContextMenuStrip.Items.Add(toolStripItem1)
        Next
    End Sub
    ' Change the cell's color.
    Private Sub toolStripItem1_Click(ByVal sender As Object, _
        ByVal args As EventArgs) _
        Handles toolStripItem1.Click

        dataGridView.Rows(mouseLocation.RowIndex) _
            .Cells(mouseLocation.ColumnIndex) _
            .Style.BackColor = Color.Red
    End Sub

    Private mouseLocation As DataGridViewCellEventArgs

    ' Deal with hovering over a cell.
    Private Sub dataGridView_CellMouseEnter(ByVal sender As Object, _
        ByVal location As DataGridViewCellEventArgs) _
        Handles DataGridView.CellMouseEnter

        mouseLocation = location
    End Sub

    Private Sub SetDefaultCellInFirstColumn()
        Dim firstColumn As DataGridViewColumn = _
            dataGridView.Columns(0)
        Dim cellStyle As DataGridViewCellStyle = _
            New DataGridViewCellStyle()
        cellStyle.BackColor = Color.Thistle

        firstColumn.DefaultCellStyle = cellStyle
    End Sub

    Private Sub ToolTips()
        Dim firstColumn As DataGridViewColumn = _
            dataGridView.Columns(0)
        Dim thirdColumn As DataGridViewColumn = _
            dataGridView.Columns(2)
        firstColumn.ToolTipText = _
            "This is column uses a default cell."
        thirdColumn.ToolTipText = _
            "This is column uses a template cell." _
            & " Changes to one cell's style changes them all."
    End Sub

    Private Sub AddAdditionalButtons()
        AddButton(Button4, "Set Minimum Width of Column Two")
        AddButton(Button5, "Set Width of Column One")
        AddButton(Button6, "Autosize Third Column")
        AddButton(Button7, "Add Thick Vertical Edge")
        AddButton(Button8, "Style and Number Columns")
        AddButton(Button9, "Change Column Header Text")
        AddButton(Button10, "Swap First and Last Columns")
    End Sub

    Private Sub AdjustDataGridViewSizing()
        dataGridView.ColumnHeadersHeightSizeMode = _
            DataGridViewColumnHeadersHeightSizeMode.AutoSize
    End Sub

    'Set the minimum width.
    Private Sub Button4_Click(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles Button4.Click

        Dim column As DataGridViewColumn = dataGridView.Columns(1)
        column.MinimumWidth = 40
    End Sub

    ' Set the width.
    Private Sub Button5_Click(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles Button5.Click

        Dim column As DataGridViewColumn = dataGridView.Columns(0)
        column.Width = 60
    End Sub

    ' AutoSize the third column.
    Private Sub Button6_Click(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles Button6.Click

        Dim column As DataGridViewColumn = dataGridView.Columns(2)
        column.AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells
    End Sub

    ' Set the vertical edge.
    Private Sub Button7_Click(ByVal sender As Object, _
        ByVal e As System.EventArgs) Handles Button7.Click

        Dim thirdColumn As Integer = 2
        Dim column As DataGridViewColumn = _
            dataGridView.Columns(thirdColumn)
        column.DividerWidth = 10

    End Sub

    ' Style and number columns.
    Private Sub Button8_Click(ByVal sender As Object, _
        ByVal args As EventArgs) Handles Button8.Click

        Dim style As DataGridViewCellStyle = _
            New DataGridViewCellStyle()
        style.Alignment = _
            DataGridViewContentAlignment.MiddleCenter
        style.ForeColor = Color.IndianRed
        style.BackColor = Color.Ivory

        For Each column As DataGridViewColumn _
            In dataGridView.Columns

            column.HeaderCell.Value = _
                column.Index.ToString
            column.HeaderCell.Style = style
        Next
    End Sub

    ' Change the text in the column header.
    Private Sub Button9_Click(ByVal sender As Object, _
        ByVal args As EventArgs) Handles Button9.Click

        For Each column As DataGridViewColumn _
            In dataGridView.Columns

            column.HeaderText = String.Concat("Column ", _
                column.Index.ToString)
        Next
    End Sub

    ' Swap the last column with the first.
    Private Sub Button10_Click(ByVal sender As Object, _
        ByVal args As EventArgs) Handles Button10.Click

        Dim columnCollection As DataGridViewColumnCollection = _
            dataGridView.Columns

        Dim firstVisibleColumn As DataGridViewColumn = _
            columnCollection.GetFirstColumn(DataGridViewElementStates.Visible)
        Dim lastVisibleColumn As DataGridViewColumn = _
            columnCollection.GetLastColumn(DataGridViewElementStates.Visible, _
            Nothing)

        Dim firstColumn_sIndex As Integer = firstVisibleColumn.DisplayIndex
        firstVisibleColumn.DisplayIndex = _
            lastVisibleColumn.DisplayIndex
        lastVisibleColumn.DisplayIndex = firstColumn_sIndex
    End Sub

    ' Updated the criteria label.
    Private Sub dataGridView_AutoSizeColumnCriteriaChanged( _
        ByVal sender As Object, _
        ByVal args As DataGridViewAutoSizeColumnModeEventArgs) _
        Handles DataGridView.AutoSizeColumnModeChanged

        args.Column.DataGridView.Parent. _
        Controls("flowlayoutpanel"). _
        Controls(criteriaLabel).Text = _
            criteriaLabel & args.Column.AutoSizeMode.ToString
    End Sub
#End Region

    <STAThreadAttribute()> _
    Public Shared Sub Main()
        Application.Run(New DataGridViewColumnDemo())
    End Sub

End Class

注解

类表示DataGridView控件中的逻辑列。 DataGridViewColumnThe DataGridViewColumn class represents a logical column in a DataGridView control. 您可以通过Columns控件的集合检索列。You can retrieve columns through the Columns collection of the control.

与包含DataGridView中的DataGridViewColumn实际单元集合的不同,主要用于调整列用户界面(UI)的外观和行为,例如列宽和DataGridViewRow单元格样式。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. 有关单元格样式的详细信息,请参阅Windows 窗体 DataGridView 控件中的单元格样式For more information about cell styles, see Cell Styles in the Windows Forms DataGridView Control.

派生自DataGridViewColumn的类型通常将CellTemplate属性初始化为派生自DataGridViewCell类的相关类型的新实例。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.

继承者说明

当从DataGridViewColumn派生类派生并向其添加新属性时,请确保Clone()重写方法以在克隆操作过程中复制新属性。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. 还应调用基类的Clone()方法,以便将基类的属性复制到新单元。You should also call the base class's Clone() method so that the properties of the base class are copied to the new cell.

构造函数

DataGridViewColumn()

DataGridViewColumn 类的新实例初始化为默认状态。Initializes a new instance of the DataGridViewColumn class to the default state.

DataGridViewColumn(DataGridViewCell)

使用现有的 DataGridViewColumn 作为模板,初始化 DataGridViewCell 类的新实例。Initializes a new instance of the DataGridViewColumn class using an existing DataGridViewCell as a template.

属性

AutoSizeMode

获取或设置模式,通过此模式列可以自动调整其宽度。Gets or sets the mode by which the column automatically adjusts its width.

CellTemplate

获取或设置用于创建新单元格的模板。Gets or sets the template used to create new cells.

CellType

获取单元格模板的运行时类型。Gets the run-time type of the cell template.

ContextMenuStrip

获取或设置列的快捷菜单。Gets or sets the shortcut menu for the column.

DataGridView

获取与此元素关联的 DataGridView 控件。Gets the DataGridView control associated with this element.

(继承自 DataGridViewElement)
DataPropertyName

获取或设置数据源属性的名称或与 DataGridViewColumn 绑定的数据库列的名称。Gets or sets the name of the data source property or database column to which the DataGridViewColumn is bound.

DefaultCellStyle

获取或设置列的默认单元格样式。Gets or sets the column's default cell style.

DefaultHeaderCellType

获取或设置默认标题单元格的运行时类型。Gets or sets the run-time type of the default header cell.

(继承自 DataGridViewBand)
Displayed

获取一个值,该值指示带区当前是否显示在屏幕上。Gets a value indicating whether the band is currently displayed onscreen.

(继承自 DataGridViewBand)
DisplayIndex

相对于当前所显示各列,获取或设置列的显示顺序。Gets or sets the display order of the column relative to the currently displayed columns.

DividerWidth

获取或设置列分隔符的宽度(以像素为单位)。Gets or sets the width, in pixels, of the column divider.

FillWeight

获取或设置一个值,表示当该列处于填充模式时,相对于控件中处于填充模式的其他列的宽度。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.

Frozen

获取或设置一个值,指示当用户水平滚动 DataGridView 控件时,列是否移动。Gets or sets a value indicating whether a column will move when a user scrolls the DataGridView control horizontally.

HasDefaultCellStyle

获取指示是否已设置 DefaultCellStyle 属性的值。Gets a value indicating whether the DefaultCellStyle property has been set.

(继承自 DataGridViewBand)
HeaderCell

获取或设置表示列标题的 DataGridViewColumnHeaderCellGets or sets the DataGridViewColumnHeaderCell that represents the column header.

HeaderCellCore

获取或设置 DataGridViewBand 的标题单元格。Gets or sets the header cell of the DataGridViewBand.

(继承自 DataGridViewBand)
HeaderText

获取或设置列标题单元格的标题文本。Gets or sets the caption text on the column's header cell.

Index

获取带区在 DataGridView 控件中的相对位置。Gets the relative position of the band within the DataGridView control.

(继承自 DataGridViewBand)
InheritedAutoSizeMode

获取对该列有效的缩放模式。Gets the sizing mode in effect for the column.

InheritedStyle

获取当前应用于该列的单元格样式。Gets the cell style currently applied to the column.

IsDataBound

获取一个值,指示该列是否绑定到某个数据源。Gets a value indicating whether the column is bound to a data source.

IsRow

获取一个值,该值指示带区是否表示一个行。Gets a value indicating whether the band represents a row.

(继承自 DataGridViewBand)
MinimumWidth

获取或设置列的最小宽度(以像素为单位)。Gets or sets the minimum width, in pixels, of the column.

Name

获取或设置列名称。Gets or sets the name of the column.

ReadOnly

获取或设置一个值,指示用户是否可以编辑列的单元格。Gets or sets a value indicating whether the user can edit the column's cells.

Resizable

获取或设置一个值,指示该列的大小是否可调。Gets or sets a value indicating whether the column is resizable.

Selected

获取或设置一个值,该值指示带区是否为被选定。Gets or sets a value indicating whether the band is in a selected user interface (UI) state.

(继承自 DataGridViewBand)
Site

获取或设置列的站点。Gets or sets the site of the column.

SortMode

获取或设置列的排序模式。Gets or sets the sort mode for the column.

State

获取元素的用户界面 (UI) 状态。Gets the user interface (UI) state of the element.

(继承自 DataGridViewElement)
Tag

获取或设置包含与带区关联的数据的对象。Gets or sets the object that contains data to associate with the band.

(继承自 DataGridViewBand)
ToolTipText

获取或设置用于工具提示的文本。Gets or sets the text used for ToolTips.

ValueType

获取或设置列单元格中值的数据类型。Gets or sets the data type of the values in the column's cells.

Visible

获取或设置一个值,指示该列是否可见。Gets or sets a value indicating whether the column is visible.

Width

获取或设置列的当前宽度。Gets or sets the current width of the column.

方法

Clone()

创建此区段的一个完全相同的副本。Creates an exact copy of this band.

Dispose()

释放由 DataGridViewBand 使用的所有资源。Releases all resources used by the DataGridViewBand.

(继承自 DataGridViewBand)
Dispose(Boolean)

释放由 DataGridViewBand 占用的非托管资源,还可以另外再释放托管资源。Releases the unmanaged resources used by the DataGridViewBand and optionally releases the managed resources.

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetPreferredWidth(DataGridViewAutoSizeColumnMode, Boolean)

根据指定条件计算列的理想宽度。Calculates the ideal width of the column based on the specified criteria.

GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
OnDataGridViewChanged()

当带区与其他 DataGridView 关联时调用。Called when the band is associated with a different DataGridView.

(继承自 DataGridViewBand)
RaiseCellClick(DataGridViewCellEventArgs)

引发 CellClick 事件。Raises the CellClick event.

(继承自 DataGridViewElement)
RaiseCellContentClick(DataGridViewCellEventArgs)

引发 CellContentClick 事件。Raises the CellContentClick event.

(继承自 DataGridViewElement)
RaiseCellContentDoubleClick(DataGridViewCellEventArgs)

引发 CellContentDoubleClick 事件。Raises the CellContentDoubleClick event.

(继承自 DataGridViewElement)
RaiseCellValueChanged(DataGridViewCellEventArgs)

引发 CellValueChanged 事件。Raises the CellValueChanged event.

(继承自 DataGridViewElement)
RaiseDataError(DataGridViewDataErrorEventArgs)

引发 DataError 事件。Raises the DataError event.

(继承自 DataGridViewElement)
RaiseMouseWheel(MouseEventArgs)

引发 MouseWheel 事件。Raises the MouseWheel event.

(继承自 DataGridViewElement)
ToString()

获取一个描述该列的字符串。Gets a string that describes the column.

事件

Disposed

释放 DataGridViewColumn 时发生。Occurs when the DataGridViewColumn is disposed.

适用于

另请参阅