Procedura dettagliata: creazione di un controllo DataGridView Windows Form non associatoWalkthrough: Creating an Unbound Windows Forms DataGridView Control

È spesso può essere utile visualizzare dati in formato tabulare che non provengono da un database.You may frequently want to display tabular data that does not originate from a database. Potrebbe ad esempio, si desidera visualizzare il contenuto di una matrice bidimensionale di stringhe.For example, you may want to show the contents of a two-dimensional array of strings. La DataGridView classe fornisce un modo semplice e personalizzabile per visualizzare i dati senza associazione a un'origine dati.The DataGridView class provides an easy and highly customizable way to display data without binding to a data source. Questa procedura dettagliata viene illustrato come popolare un DataGridView controllare e gestire l'aggiunta e l'eliminazione di righe in modalità "associata".This walkthrough shows how to populate a DataGridView control and manage the addition and deletion of rows in "unbound" mode. Per impostazione predefinita, l'utente può aggiungere nuove righe.By default, the user can add new rows. Per impedire l'aggiunta delle righe, impostare il AllowUserToAddRows proprietà false.To prevent row addition, set the AllowUserToAddRows property is false.

Per copiare il codice in questo argomento come elenco singolo, vedere procedura: creare un controllo DataGridView di Windows Form non associato.To copy the code in this topic as a single listing, see How to: Create an Unbound Windows Forms DataGridView Control.

Creazione del formCreating the Form

Per utilizzare un controllo DataGridView non associatoTo use an unbound DataGridView control

  1. Creare una classe che deriva da Form e contiene le seguenti dichiarazioni di variabili e Main metodo.Create a class that derives from Form and contains the following variable declarations and Main method.

    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();
    
    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()]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new Form1());
        }
    }
    
    
        <STAThreadAttribute()> _
        Public Shared Sub Main()
            Application.EnableVisualStyles()
            Application.Run(New Form1())
        End Sub
    
    End Class
    
  2. Implementare un SetupLayout metodo nella definizione di classe del form per impostare il layout del form.Implement a SetupLayout method in your form's class definition to set up the form's layout.

    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);
    }
    
    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
    
  3. Creare un SetupDataGridView metodo per impostare il DataGridView colonne e le proprietà.Create a SetupDataGridView method to set up the DataGridView columns and properties.

    Questo metodo aggiunge il DataGridView controllo sul form Controls insieme.This method first adds the DataGridView control to the form's Controls collection. Successivamente, il numero di colonne da visualizzare viene impostato mediante il ColumnCount proprietà.Next, the number of columns to be displayed is set using the ColumnCount property. Lo stile predefinito per le intestazioni di colonna è impostato tramite l'impostazione di BackColor, ForeColor, e Font le proprietà del DataGridViewCellStyle restituito dal ColumnHeadersDefaultCellStyle proprietà.The default style for the column headers is set by setting the BackColor, ForeColor, and Font properties of the DataGridViewCellStyle returned by the ColumnHeadersDefaultCellStyle property.

    Vengono impostate le proprietà di layout e l'aspetto, e quindi vengono assegnati i nomi di colonna.Layout and appearance properties are set, and then the column names are assigned. Quando questo metodo termina, il DataGridView controllo è pronto per essere compilato.When this method exits, the DataGridView control is ready to be populated.

    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);
    }
    
    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
    
  4. Creare un PopulateDataGridView metodo a cui aggiungere righe di DataGridView controllo.Create a PopulateDataGridView method to add rows to the DataGridView control.

    Ogni riga rappresenta un brano e le informazioni associate.Each row represents a song and its associated information.

    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;
    }
    
    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
    
  5. Con i metodi di utilità sul posto, è possibile collegare i gestori di eventi.With the utility methods in place, you can attach event handlers.

    È necessario gestire il Aggiungi e eliminare dei pulsanti Click eventi, il modulo Load evento e DataGridView del controllo CellFormatting evento.You will handle the Add and Delete buttons' Click events, the form's Load event, and the DataGridView control's CellFormatting event.

    Quando il Aggiungi del pulsante Click una nuova riga vuota, viene generato l'evento, viene aggiunto per il DataGridView.When the Add button's Click event is raised, a new, empty row is added to the DataGridView.

    Quando il eliminare del pulsante Click viene generato l'evento, viene eliminata la riga selezionata, a meno che non è la riga per nuovi record, che consente all'utente di aggiungere nuove righe.When the Delete button's Click event is raised, the selected row is deleted, unless it is the row for new records, which enables the user add new rows. Questa riga è sempre l'ultima riga di DataGridView controllo.This row is always the last row in the DataGridView control.

    Quando il modulo Load viene generato l'evento, il SetupLayout, SetupDataGridView, e PopulateDataGridView vengono chiamati i metodi di utilità.When the form's Load event is raised, the SetupLayout, SetupDataGridView, and PopulateDataGridView utility methods are called.

    Quando il CellFormatting evento viene generato, ogni cella di Date colonna in formato data estesa, a meno che il valore della cella non può essere analizzato.When the CellFormatting event is raised, each cell in the Date column is formatted as a long date, unless the cell's value cannot be parsed.

    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 (e != null)
        {
            if (this.songsDataGridView.Columns[e.ColumnIndex].Name == "Release Date")
            {
                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);
        }
    }
    
    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 e IsNot Nothing Then
    
            If Me.songsDataGridView.Columns(e.ColumnIndex).Name = _
            "Release Date" 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
    

Verifica dell'applicazioneTesting the Application

È ora possibile testare il form per assicurarsi che tutto funzioni come previsto.You can now test the form to make sure it behaves as expected.

Per verificare il moduloTo test the form

  • Premere F5 per eseguire l'applicazione.Press F5 to run the application.

    Verrà visualizzato un DataGridView controllo che visualizza le canzoni elencate in PopulateDataGridView.You will see a DataGridView control that displays the songs listed in PopulateDataGridView. È possibile aggiungere nuove righe con la Aggiungi riga e sarà possibile eliminare righe selezionate con il Elimina riga pulsante.You can add new rows with the Add Row button, and you can delete selected rows with the Delete Row button. La cornice DataGridView controllo è l'archivio dati e i dati sono indipendenti da qualsiasi origine esterna, ad esempio un DataSet o una matrice.The unbound DataGridView control is the data store, and its data is independent of any external source, such as a DataSet or an array.

Passaggi successiviNext Steps

Questa applicazione fornisce una conoscenza di base di DataGridView funzionalità del controllo.This application gives you a basic understanding of the DataGridView control's capabilities. È possibile personalizzare l'aspetto e il comportamento del DataGridView controllo in diversi modi:You can customize the appearance and behavior of the DataGridView control in several ways:

Vedere ancheSee Also

DataGridView
Visualizzazione di dati nel controllo DataGridView di Windows FormDisplaying Data in the Windows Forms DataGridView Control
Procedura: Creare un controllo DataGridView di Windows Form non associatoHow to: Create an Unbound Windows Forms DataGridView Control
Modalità di visualizzazione di dati nel controllo DataGridView di Windows FormData Display Modes in the Windows Forms DataGridView Control