Procedura: accedere a oggetti associati a righe DataGridView di Windows FormHow to: Access Objects Bound to Windows Forms DataGridView Rows

A volte è utile visualizzare una tabella di informazioni archiviate in una raccolta di oggetti business.Sometimes it is useful to display a table of information stored in a collection of business objects. Quando si associa un controllo DataGridView a una raccolta di questo tipo, ogni proprietà pubblica viene visualizzata nella rispettiva colonna, a meno che la proprietà non sia stata contrassegnata come non visualizzabile con BrowsableAttribute.When you bind a DataGridView control to such a collection, each public property is displayed in its own column unless the property has been marked non-browsable with a BrowsableAttribute. Ad esempio, una raccolta di oggetti Customer avrebbe colonne come Nome e Indirizzo.For example, a collection of Customer objects would have columns such as Name and Address.

Se questi oggetti contengono informazioni aggiuntive e codice a cui si desidera accedere, è possibile raggiungerli tramite gli oggetti riga.If these objects contain additional information and code that you want to access, you can reach it through row objects. Nell'esempio di codice riportato di seguito, gli utenti possono selezionare più righe e fare clic su un pulsante per inviare una fattura a ogni cliente corrispondente.In the following code example, users can select multiple rows and click a button to send an invoice to each of the corresponding customers.

Per accedere agli oggetti associati a righeTo access row-bound objects

  • Usare la proprietà DataGridViewRow.DataBoundItem.Use the DataGridViewRow.DataBoundItem property.

    void invoiceButton_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)
        {
            Customer cust = row.DataBoundItem as Customer;
            if (cust != null)
            {
                cust.SendInvoice();
            }
        }
    }
    
    Private Sub InvoiceButton_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles InvoiceButton.Click
    
        For Each row As DataGridViewRow In Me.DataGridView1.SelectedRows
    
            Dim cust As Customer = TryCast(row.DataBoundItem, Customer)
            If cust IsNot Nothing Then
                cust.SendInvoice()
            End If
    
        Next
    
    End Sub
    

EsempioExample

L'esempio di codice completo include una semplice implementazione Customer e associa DataGridView a un oggetto ArrayList contenente alcuni oggetti Customer.The complete code example includes a simple Customer implementation and binds the DataGridView to an ArrayList containing a few Customer objects. Il gestore dell'evento Click di System.Windows.Forms.Button deve accedere agli oggetti Customer tramite le righe, perché la raccolta di clienti non è accessibile al di fuori del gestore dell'evento Form.Load.The Click event handler of the System.Windows.Forms.Button must access the Customer objects through the rows, because the customer collection is not accessible outside the Form.Load event handler.

using System;
using System.Windows.Forms;

public class DataGridViewObjectBinding : Form
{
    // These declarations and the Main() and New() methods 
    // below can be replaced with designer-generated code. 
    private Button invoiceButton = new Button();
    private DataGridView dataGridView1 = new DataGridView();

    // Entry point code. 
    [STAThreadAttribute()]
    public static void Main()
    {
        Application.Run(new DataGridViewObjectBinding());
    }

    // Sets up the form.
    public DataGridViewObjectBinding()
    {
        this.dataGridView1.Dock = DockStyle.Fill;
        this.Controls.Add(this.dataGridView1);

        this.invoiceButton.Text = "invoice the selected customers";
        this.invoiceButton.Dock = DockStyle.Top;
        this.invoiceButton.Click += new EventHandler(invoiceButton_Click);
        this.Controls.Add(this.invoiceButton);

        this.Load += new EventHandler(DataGridViewObjectBinding_Load);
        this.Text = "DataGridView collection-binding demo";
    }

    void  DataGridViewObjectBinding_Load(object sender, EventArgs e)
    {
        // Set up a collection of objects for binding.
        System.Collections.ArrayList customers = new System.Collections.ArrayList();
        customers.Add(new Customer("Harry"));
        customers.Add(new Customer("Sally"));
        customers.Add(new Customer("Roy"));
        customers.Add(new Customer("Pris"));

        // Initialize and bind the DataGridView.
        this.dataGridView1.SelectionMode = 
            DataGridViewSelectionMode.FullRowSelect;
        this.dataGridView1.AutoGenerateColumns = true;
        this.dataGridView1.DataSource = customers;
    }

    // Calls the SendInvoice() method for the Customer 
    // object bound to each selected row.
    void invoiceButton_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in this.dataGridView1.SelectedRows)
        {
            Customer cust = row.DataBoundItem as Customer;
            if (cust != null)
            {
                cust.SendInvoice();
            }
        }
    }
}

public class Customer
{
    private String nameValue;

    public Customer(String name)
    {
        nameValue = name;
    }

    public String Name
    {
        get
        {
            return nameValue;
        }
        set 
        {
            nameValue = value;
        }
    }

    public void SendInvoice()
    {
        MessageBox.Show(nameValue + " has been billed.");
    }
}
Imports System
Imports System.Windows.Forms

Public Class DataGridViewObjectBinding
    Inherits Form

    ' These declarations and the Main() and New() methods 
    ' below can be replaced with designer-generated code. 
    Private WithEvents InvoiceButton As New Button()
    Private WithEvents DataGridView1 As New DataGridView()

    ' Entry point code. 
    <STAThreadAttribute()> _
    Public Shared Sub Main()

        Application.Run(New DataGridViewObjectBinding())

    End Sub

    ' Sets up the form. 
    Public Sub New()

        Me.DataGridView1.Dock = DockStyle.Fill
        Me.Controls.Add(Me.DataGridView1)

        Me.InvoiceButton.Text = "invoice the selected customers"
        Me.InvoiceButton.Dock = DockStyle.Top
        Me.Controls.Add(Me.InvoiceButton)
        Me.Text = "DataGridView collection-binding demo"

    End Sub

    Private Sub Form1_Load(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles MyBase.Load

        ' Set up a collection of objects for binding.
        Dim customers As New System.Collections.ArrayList()
        customers.Add(New Customer("Harry"))
        customers.Add(New Customer("Sally"))
        customers.Add(New Customer("Roy"))
        customers.Add(New Customer("Pris"))

        ' Initialize and bind the DataGridView.
        Me.DataGridView1.SelectionMode = _
            DataGridViewSelectionMode.FullRowSelect
        Me.DataGridView1.AutoGenerateColumns = True
        Me.DataGridView1.DataSource = customers

    End Sub

    ' Calls the SendInvoice() method for the Customer 
    ' object bound to each selected row.
    Private Sub InvoiceButton_Click(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles InvoiceButton.Click

        For Each row As DataGridViewRow In Me.DataGridView1.SelectedRows

            Dim cust As Customer = TryCast(row.DataBoundItem, Customer)
            If cust IsNot Nothing Then
                cust.SendInvoice()
            End If

        Next

    End Sub

End Class

Public Class Customer

    Private nameValue As String

    Public Sub New(ByVal name As String)
        nameValue = name
    End Sub

    Public Property Name() As String
        Get
            Return nameValue
        End Get
        Set(ByVal value As String)
            nameValue = value
        End Set
    End Property

    Public Sub SendInvoice()
        MsgBox(nameValue & " has been billed.")
    End Sub

End Class

Compilazione del codiceCompiling the Code

L'esempio presenta i requisiti seguenti:This example requires:

  • Riferimenti agli assembly System e System.Windows.Forms.References to the System and System.Windows.Forms assemblies.

Per informazioni sulla compilazione di questo esempio dalla riga di comando per Visual Basic o Visual c#, vedere compilazione dalla riga di comando oppure con la creazione della riga di comando csc.exe.For information about building this example from the command line for Visual Basic or Visual C#, see Building from the Command Line or Command-line Building With csc.exe. È anche possibile compilare questo esempio in Visual Studio incollando il codice in un nuovo progetto.You can also build this example in Visual Studio by pasting the code into a new project. Vedere anche Procedura: Compilare ed eseguire un esempio di codice Windows Form completo con Visual Studio.Also see How to: Compile and Run a Complete Windows Forms Code Example Using Visual Studio.

Vedere ancheSee Also

DataGridView
DataGridViewRow
DataGridViewRow.DataBoundItem
Visualizzazione di dati nel controllo DataGridView di Windows FormDisplaying Data in the Windows Forms DataGridView Control
Procedura: Associare oggetti ai controlli DataGridView di Windows FormsHow to: Bind Objects to Windows Forms DataGridView Controls