次の方法で共有


チュートリアル : バインドされていない Windows フォーム DataGridView コントロールの作成

更新 : 2007 年 11 月

データベースから取得したものではないデータを表形式で表示しなければならない場合はよくあります。たとえば、文字列の 2 次元配列の内容を表示する場合などです。DataGridView クラスは、データ ソースにバインドせずにデータを表示するための、簡単で高度にカスタマイズ可能な手段となります。このチュートリアルでは、DataGridView コントロールのデータを手動で作成し、行の追加と削除を非バインド モードで管理する方法を示します。既定では、ユーザーが新しい行を追加できます。行の追加を防ぐには、AllowUserToAddRows プロパティを false に設定します。

このトピックのコードを単一のリストとしてコピーするには、「方法 : 連結されていない Windows フォーム DataGridView コントロールを作成する」を参照してください。

フォームの作成

バインドされていない DataGridView コントロールを使用するには

  1. Form から派生したクラスを作成し、次の変数宣言と Main メソッドを含めます。

    Imports System
    Imports System.Drawing
    Imports System.Windows.Forms
    
    Public Class Form1
        Inherits System.Windows.Forms.Form
    
        Private buttonPanel As New Panel
        Private WithEvents songsDataGridView As New DataGridView
        Private WithEvents addNewRowButton As New Button
        Private WithEvents deleteRowButton As New Button
    
    
    ...
    
    
    
        <STAThreadAttribute()> _
        Public Shared Sub Main()
            Application.EnableVisualStyles()
            Application.Run(New Form1())
        End Sub
    
    End Class
    
    using System;
    using System.Drawing;
    using System.Windows.Forms;
    
    public class Form1 : System.Windows.Forms.Form
    {
        private Panel buttonPanel = new Panel();
        private DataGridView songsDataGridView = new DataGridView();
        private Button addNewRowButton = new Button();
        private Button deleteRowButton = new Button();
    
    
    ...
    
    
    
        [STAThreadAttribute()]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }
    }
    
  2. フォームのクラス定義の中に、フォームのレイアウトをセットアップするための SetupLayout メソッドを実装します。

    Private Sub SetupLayout()
    
        Me.Size = New Size(600, 500)
    
        With addNewRowButton
            .Text = "Add Row"
            .Location = New Point(10, 10)
        End With
    
        With deleteRowButton
            .Text = "Delete Row"
            .Location = New Point(100, 10)
        End With
    
        With buttonPanel
            .Controls.Add(addNewRowButton)
            .Controls.Add(deleteRowButton)
            .Height = 50
            .Dock = DockStyle.Bottom
        End With
    
        Me.Controls.Add(Me.buttonPanel)
    
    End Sub
    
    private void SetupLayout()
    {
        this.Size = new Size(600, 500);
    
        addNewRowButton.Text = "Add Row";
        addNewRowButton.Location = new Point(10, 10);
        addNewRowButton.Click += new EventHandler(addNewRowButton_Click);
    
        deleteRowButton.Text = "Delete Row";
        deleteRowButton.Location = new Point(100, 10);
        deleteRowButton.Click += new EventHandler(deleteRowButton_Click);
    
        buttonPanel.Controls.Add(addNewRowButton);
        buttonPanel.Controls.Add(deleteRowButton);
        buttonPanel.Height = 50;
        buttonPanel.Dock = DockStyle.Bottom;
    
        this.Controls.Add(this.buttonPanel);
    }
    
  3. DataGridView の列とプロパティをセットアップするための SetupDataGridView メソッドを作成します。

    このメソッドでは、まず DataGridView コントロールをフォームの Controls コレクションに追加します。次に、ColumnCount プロパティを使用して、表示する列の数を設定します。さらに、列ヘッダーの既定のスタイルを設定するために、ColumnHeadersDefaultCellStyle プロパティによって返される DataGridViewCellStyleBackColorForeColor、および Font プロパティを設定します。

    レイアウトと外観に関するプロパティを設定したら、次は列名を割り当てます。このメソッドが終了すると、DataGridView コントロールにデータを追加できる状態になります。

    Private Sub SetupDataGridView()
    
        Me.Controls.Add(songsDataGridView)
    
        songsDataGridView.ColumnCount = 5
        With songsDataGridView.ColumnHeadersDefaultCellStyle
            .BackColor = Color.Navy
            .ForeColor = Color.White
            .Font = New Font(songsDataGridView.Font, FontStyle.Bold)
        End With
    
        With songsDataGridView
            .Name = "songsDataGridView"
            .Location = New Point(8, 8)
            .Size = New Size(500, 250)
            .AutoSizeRowsMode = _
                DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders
            .ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Single
            .CellBorderStyle = DataGridViewCellBorderStyle.Single
            .GridColor = Color.Black
            .RowHeadersVisible = False
    
            .Columns(0).Name = "Release Date"
            .Columns(1).Name = "Track"
            .Columns(2).Name = "Title"
            .Columns(3).Name = "Artist"
            .Columns(4).Name = "Album"
            .Columns(4).DefaultCellStyle.Font = _
                New Font(Me.songsDataGridView.DefaultCellStyle.Font, FontStyle.Italic)
    
            .SelectionMode = DataGridViewSelectionMode.FullRowSelect
            .MultiSelect = False
            .Dock = DockStyle.Fill
        End With
    
    End Sub
    
    private void SetupDataGridView()
    {
        this.Controls.Add(songsDataGridView);
    
        songsDataGridView.ColumnCount = 5;
    
        songsDataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.Navy;
        songsDataGridView.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
        songsDataGridView.ColumnHeadersDefaultCellStyle.Font =
            new Font(songsDataGridView.Font, FontStyle.Bold);
    
        songsDataGridView.Name = "songsDataGridView";
        songsDataGridView.Location = new Point(8, 8);
        songsDataGridView.Size = new Size(500, 250);
        songsDataGridView.AutoSizeRowsMode =
            DataGridViewAutoSizeRowsMode.DisplayedCellsExceptHeaders;
        songsDataGridView.ColumnHeadersBorderStyle =
            DataGridViewHeaderBorderStyle.Single;
        songsDataGridView.CellBorderStyle = DataGridViewCellBorderStyle.Single;
        songsDataGridView.GridColor = Color.Black;
        songsDataGridView.RowHeadersVisible = false;
    
        songsDataGridView.Columns[0].Name = "Release Date";
        songsDataGridView.Columns[1].Name = "Track";
        songsDataGridView.Columns[2].Name = "Title";
        songsDataGridView.Columns[3].Name = "Artist";
        songsDataGridView.Columns[4].Name = "Album";
        songsDataGridView.Columns[4].DefaultCellStyle.Font =
            new Font(songsDataGridView.DefaultCellStyle.Font, FontStyle.Italic);
    
        songsDataGridView.SelectionMode =
            DataGridViewSelectionMode.FullRowSelect;
        songsDataGridView.MultiSelect = false;
        songsDataGridView.Dock = DockStyle.Fill;
    
        songsDataGridView.CellFormatting += new
            DataGridViewCellFormattingEventHandler(
            songsDataGridView_CellFormatting);
    }
    
  4. DataGridView コントロールに行を追加するための PopulateDataGridView メソッドを作成します。

    各行は、歌とその関連情報を表しています。

    Private Sub PopulateDataGridView()
    
        Dim row0 As String() = {"11/22/1968", "29", "Revolution 9", _
            "Beatles", "The Beatles [White Album]"}
        Dim row1 As String() = {"1960", "6", "Fools Rush In", _
            "Frank Sinatra", "Nice 'N' Easy"}
        Dim row2 As String() = {"11/11/1971", "1", "One of These Days", _
            "Pink Floyd", "Meddle"}
        Dim row3 As String() = {"1988", "7", "Where Is My Mind?", _
            "Pixies", "Surfer Rosa"}
        Dim row4 As String() = {"5/1981", "9", "Can't Find My Mind", _
            "Cramps", "Psychedelic Jungle"}
        Dim row5 As String() = {"6/10/2003", "13", _
            "Scatterbrain. (As Dead As Leaves.)", _
            "Radiohead", "Hail to the Thief"}
        Dim row6 As String() = {"6/30/1992", "3", "Dress", "P J Harvey", "Dry"}
    
        With Me.songsDataGridView.Rows
            .Add(row0)
            .Add(row1)
            .Add(row2)
            .Add(row3)
            .Add(row4)
            .Add(row5)
            .Add(row6)
        End With
    
        With Me.songsDataGridView
            .Columns(0).DisplayIndex = 3
            .Columns(1).DisplayIndex = 4
            .Columns(2).DisplayIndex = 0
            .Columns(3).DisplayIndex = 1
            .Columns(4).DisplayIndex = 2
        End With
    
    End Sub
    
    private void PopulateDataGridView()
    {
    
        string[] row0 = { "11/22/1968", "29", "Revolution 9", 
            "Beatles", "The Beatles [White Album]" };
        string[] row1 = { "1960", "6", "Fools Rush In", 
            "Frank Sinatra", "Nice 'N' Easy" };
        string[] row2 = { "11/11/1971", "1", "One of These Days", 
            "Pink Floyd", "Meddle" };
        string[] row3 = { "1988", "7", "Where Is My Mind?", 
            "Pixies", "Surfer Rosa" };
        string[] row4 = { "5/1981", "9", "Can't Find My Mind", 
            "Cramps", "Psychedelic Jungle" };
        string[] row5 = { "6/10/2003", "13", 
            "Scatterbrain. (As Dead As Leaves.)", 
            "Radiohead", "Hail to the Thief" };
        string[] row6 = { "6/30/1992", "3", "Dress", "P J Harvey", "Dry" };
    
        songsDataGridView.Rows.Add(row0);
        songsDataGridView.Rows.Add(row1);
        songsDataGridView.Rows.Add(row2);
        songsDataGridView.Rows.Add(row3);
        songsDataGridView.Rows.Add(row4);
        songsDataGridView.Rows.Add(row5);
        songsDataGridView.Rows.Add(row6);
    
        songsDataGridView.Columns[0].DisplayIndex = 3;
        songsDataGridView.Columns[1].DisplayIndex = 4;
        songsDataGridView.Columns[2].DisplayIndex = 0;
        songsDataGridView.Columns[3].DisplayIndex = 1;
        songsDataGridView.Columns[4].DisplayIndex = 2;
    }
    
  5. ユーティリティ メソッドを定義したら、次はイベント ハンドラを追加します。

    [Add] ボタンと [Delete] ボタンの Click イベント、フォームの Load イベント、さらに DataGridView コントロールの CellFormatting イベントを処理します。

    [Add] ボタンの Click イベントが発生したときは、新しい空の行を DataGridView に追加します。

    [Delete] ボタンの Click イベントが発生したときは、選択中の行が新規レコード用の行 (ユーザーが新しい行を追加するときに使用) でない限り、選択中の行を削除します。この行は、必ず DataGridView コントロールの最後の行になります。

    フォームの Load イベントが発生したときは、SetupLayout、SetupDataGridView、PopulateDataGridView というユーティリティ メソッドを呼び出します。

    CellFormatting イベントが発生したときは、Date 列の各セルを長い形式の日付に書式設定します (セルの値が解析できない場合を除く)。

    Private Sub Form1_Load(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles MyBase.Load
    
        SetupLayout()
        SetupDataGridView()
        PopulateDataGridView()
    
    End Sub
    
    Private Sub songsDataGridView_CellFormatting(ByVal sender As Object, _
        ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) _
        Handles songsDataGridView.CellFormatting
    
        If Me.songsDataGridView.Columns(e.ColumnIndex).Name = _
            "Release Date" Then
    
            If e IsNot Nothing Then
                If e.Value IsNot Nothing Then
                    Try
                        e.Value = DateTime.Parse(e.Value.ToString()) _
                            .ToLongDateString()
                        e.FormattingApplied = True
                    Catch ex As FormatException
                        Console.WriteLine("{0} is not a valid date.", e.Value.ToString())
                    End Try
                End If
            End If
    
        End If
    
    End Sub
    
    Private Sub addNewRowButton_Click(ByVal sender As Object, _
        ByVal e As EventArgs) Handles addNewRowButton.Click
    
        Me.songsDataGridView.Rows.Add()
    
    End Sub
    
    Private Sub deleteRowButton_Click(ByVal sender As Object, _
        ByVal e As EventArgs) Handles deleteRowButton.Click
    
        If Me.songsDataGridView.SelectedRows.Count > 0 AndAlso _
            Not Me.songsDataGridView.SelectedRows(0).Index = _
            Me.songsDataGridView.Rows.Count - 1 Then
    
            Me.songsDataGridView.Rows.RemoveAt( _
                Me.songsDataGridView.SelectedRows(0).Index)
    
        End If
    
    End Sub
    
    public Form1()
    {
        this.Load += new EventHandler(Form1_Load);
    }
    
    private void Form1_Load(System.Object sender, System.EventArgs e)
    {
        SetupLayout();
        SetupDataGridView();
        PopulateDataGridView();
    }
    
    private void songsDataGridView_CellFormatting(object sender,
        System.Windows.Forms.DataGridViewCellFormattingEventArgs e)
    {
        if (this.songsDataGridView.Columns[e.ColumnIndex].Name == "Release Date")
        {
            if (e != null)
            {
                if (e.Value != null)
                {
                    try
                    {
                        e.Value = DateTime.Parse(e.Value.ToString())
                            .ToLongDateString();
                        e.FormattingApplied = true;
                    }
                    catch (FormatException)
                    {
                        Console.WriteLine("{0} is not a valid date.", e.Value.ToString());
                    }
                }
            }
        }
    }
    
    private void addNewRowButton_Click(object sender, EventArgs e)
    {
        this.songsDataGridView.Rows.Add();
    }
    
    private void deleteRowButton_Click(object sender, EventArgs e)
    {
        if (this.songsDataGridView.SelectedRows.Count > 0 &&
            this.songsDataGridView.SelectedRows[0].Index !=
            this.songsDataGridView.Rows.Count - 1)
        {
            this.songsDataGridView.Rows.RemoveAt(
                this.songsDataGridView.SelectedRows[0].Index);
        }
    }
    

アプリケーションのテスト

フォームをテストして、期待どおりに動作することを確認します。

フォームをテストするには

  • F5 キーを押してアプリケーションを実行します。

    PopulateDataGridView 内で指定した歌の一覧を含む DataGridView コントロールが表示されます。[Add Row] ボタンをクリックすると新しい行を追加でき、[Delete Row] ボタンをクリックすると選択中の行を削除できます。このバインドされていない DataGridView コントロールはそれ自体がデータ ストアであり、このデータは DataSet や配列などの外部ソースに依存していません。

次の手順

このアプリケーションでは、DataGridView コントロールの基本的な機能を学ぶことができます。DataGridView コントロールの外観と動作はいくつかの方法でカスタマイズできます。

参照

処理手順

方法 : 連結されていない Windows フォーム DataGridView コントロールを作成する

概念

Windows フォーム DataGridView コントロールでのデータ表示モード

参照

DataGridView

その他の技術情報

Windows フォーム DataGridView コントロールでのデータの表示