英語で読む

次の方法で共有


DataGridViewColumn クラス

定義

DataGridView コントロールの列を表します。

[System.ComponentModel.TypeConverter(typeof(System.Windows.Forms.DataGridViewColumnConverter))]
public class DataGridViewColumn : System.Windows.Forms.DataGridViewBand, IDisposable, System.ComponentModel.IComponent
継承
派生
属性
実装

次のコード例では、 と ボタンのセットを DataGridView 使用して Windows フォームを作成します。 各ボタン ラベルには、最初と最後の列の入れ替え (プロパティを使用) や列ヘッダーのテキストの変更 (プロパティを使用DisplayIndex) など、プロパティに関連するDataGridViewColumn操作がHeaderText記述されています。 ボタンをクリックすると、 の関連付けられたプロパティが変更されます 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());
    }
}

注釈

クラスは DataGridViewColumn 、コントロール内の論理列を DataGridView 表します。 コントロールのコレクションを Columns 使用して列を取得できます。

DataGridViewRow内のセルDataGridViewDataGridViewColumnの実際のコレクションを含む とは異なり、主に列の幅やセル スタイルなど、列ユーザー インターフェイス (UI) の外観と動作を調整するために使用されます。 セル スタイルの詳細については、「Windows フォーム DataGridView コントロールでのセルのスタイル」を参照してください。

から派生する型は、通常、 CellTemplate クラスからDataGridViewColumn派生した関連する型の新しいインスタンスに プロパティをDataGridViewCell初期化します。 個々のセルの外観または動作に関連する列プロパティは、テンプレート セルの対応するプロパティのラッパーです。 列でこれらのプロパティのいずれかを変更すると、セル テンプレートと列内のすべてのセルの値が自動的に変更されます。 個々のセルに対して指定した値をオーバーライドするには、列の値を設定した後にセル値を設定します。

注意 (継承者)

から DataGridViewColumn 派生し、派生クラスに新しいプロパティを追加するときは、必ず メソッドを Clone() オーバーライドして、複製操作中に新しいプロパティをコピーしてください。 基底クラスの Clone() プロパティが新しいセルにコピーされるように、基底クラスの メソッドも呼び出す必要があります。

コンストラクター

DataGridViewColumn()

DataGridViewColumn クラスの新しいインスタンスを既定の状態に初期化します。

DataGridViewColumn(DataGridViewCell)

既存の DataGridViewColumn をテンプレートとして使用して、DataGridViewCell クラスの新しいインスタンスを初期化します。

プロパティ

AutoSizeMode

列の幅を自動的に調整するときに使用するモードを取得または設定します。

CellTemplate

新しいセルの作成に使用するテンプレートを取得または設定します。

CellType

セル テンプレートのランタイム型を取得します。

ContextMenuStrip

列のショートカット メニューを取得または設定します。

DataGridView

この要素に関連付けられている DataGridView コントロールを取得します。

(継承元 DataGridViewElement)
DataPropertyName

DataGridViewColumn がバインドされている、データ ソース プロパティの名前またはデータベースの列の名前を取得または設定します。

DefaultCellStyle

列の既定のセル スタイルを取得または設定します。

DefaultHeaderCellType

既定のヘッダー セルのランタイム型を取得または設定します。

(継承元 DataGridViewBand)
Displayed

バンドが現在画面に表示されているかどうかを示す値を取得します。

(継承元 DataGridViewBand)
DisplayIndex

現在表示されている列を基準とした列の表示順序を設定または取得します。

DividerWidth

列の区分線の幅 (ピクセル数) を取得または設定します。

FillWeight

列が、コントロール内の他の塗りつぶしモードの列の幅を基準とする塗りつぶしモードの場合、列の幅を表す値を取得または設定します。

Frozen

ユーザーが DataGridView コントロールを水平方向にスクロールしたときに列が移動するかどうかを示す値を取得または設定します。

HasDefaultCellStyle

DefaultCellStyle プロパティが設定されているかどうかを示す値を取得します。

(継承元 DataGridViewBand)
HeaderCell

列ヘッダーを表す DataGridViewColumnHeaderCell を取得または設定します。

HeaderCellCore

DataGridViewBand のヘッダー セルを取得または設定します。

(継承元 DataGridViewBand)
HeaderText

列のヘッダー セルのキャプション テキストを取得または設定します。

Index

DataGridView コントロール内のバンドの相対位置を取得します。

(継承元 DataGridViewBand)
InheritedAutoSizeMode

列に対して有効なサイズ変更モードを取得します。

InheritedStyle

列に現在適用されているセル スタイルを取得します。

IsDataBound

列がデータ ソースにバインドされているかどうかを示す値を取得します。

IsRow

バンドが行を表すかどうかを示す値を取得します。

(継承元 DataGridViewBand)
MinimumWidth

列の最小幅をピクセル単位で取得または設定します。

Name

列の名前を取得または設定します。

ReadOnly

ユーザーが列のセルを編集できるかどうかを示す値を取得または設定します。

Resizable

列のサイズを変更できるかどうかを示す値を取得または設定します。

Selected

バンドが、選択されたユーザー インターフェイス (UI) 状態かどうかを示す値を取得または設定します。

(継承元 DataGridViewBand)
Site

列のサイトを取得または設定します。

SortMode

列の並べ替えモードを取得または設定します。

State

要素のユーザー インターフェイス (UI) の状態を取得します。

(継承元 DataGridViewElement)
Tag

バンドに関連付けられているデータを含むオブジェクトを取得または設定します。

(継承元 DataGridViewBand)
ToolTipText

ツールヒントに使用されるテキストを取得または設定します。

ValueType

列のセルの値のデータ型を取得または設定します。

Visible

列が表示されているかどうかを示す値を取得または設定します。

Width

列の現在の幅を取得または設定します。

メソッド

Clone()

このバンドの同一コピーを作成します。

Dispose()

DataGridViewBand によって使用されているすべてのリソースを解放します。

(継承元 DataGridViewBand)
Dispose(Boolean)

DataGridViewBand によって使用されているアンマネージド リソースを解放し、オプションでマネージド リソースも解放します。

Equals(Object)

指定されたオブジェクトが現在のオブジェクトと等しいかどうかを判断します。

(継承元 Object)
GetHashCode()

既定のハッシュ関数として機能します。

(継承元 Object)
GetPreferredWidth(DataGridViewAutoSizeColumnMode, Boolean)

指定した基準に基づいて、列の適切な幅を計算します。

GetType()

現在のインスタンスの Type を取得します。

(継承元 Object)
MemberwiseClone()

現在の Object の簡易コピーを作成します。

(継承元 Object)
OnDataGridViewChanged()

バンドが別の DataGridView に関連付けられている場合に呼び出されます。

(継承元 DataGridViewBand)
RaiseCellClick(DataGridViewCellEventArgs)

CellClick イベントを発生させます。

(継承元 DataGridViewElement)
RaiseCellContentClick(DataGridViewCellEventArgs)

CellContentClick イベントを発生させます。

(継承元 DataGridViewElement)
RaiseCellContentDoubleClick(DataGridViewCellEventArgs)

CellContentDoubleClick イベントを発生させます。

(継承元 DataGridViewElement)
RaiseCellValueChanged(DataGridViewCellEventArgs)

CellValueChanged イベントを発生させます。

(継承元 DataGridViewElement)
RaiseDataError(DataGridViewDataErrorEventArgs)

DataError イベントを発生させます。

(継承元 DataGridViewElement)
RaiseMouseWheel(MouseEventArgs)

MouseWheel イベントを発生させます。

(継承元 DataGridViewElement)
ToString()

列を説明する文字列を取得します。

イベント

Disposed

DataGridViewColumn が破棄されたときに発生します。

適用対象

製品 バージョン
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10

こちらもご覧ください