Procedura: associare un controllo Windows Form a un tipoHow to: Bind a Windows Forms Control to a Type

Quando si compilano controlli che interagiscono con i dati, a volte è necessario associare un controllo a un tipo, invece che a un oggetto.When you are building controls that interact with data, you will sometimes find it necessary to bind a control to a type, rather than an object. Questa situazione si verifica soprattutto in fase di progettazione, quando i dati potrebbero non essere disponibili, ma i controlli associati a dati devono visualizzare informazioni provenienti dall'interfaccia pubblica di un tipo.This situation arises especially at design time, when data may not be available, but your data-bound controls still need to display information from a type's public interface. Ad esempio, se si associa un controllo DataGridView a un oggetto esposto da un servizio Web, potrebbe essere necessario che in fase di progettazione il controllo DataGridView assegni alle colonne un'etichetta con i nomi dei membri di un tipo personalizzato.For example, you may bind a DataGridView control to an object exposed by a Web service and want the DataGridView control to label its columns at design time with the member names of a custom type.

È possibile associare facilmente un controllo a un tipo con il componente BindingSource.You can easily bind a control to a type with the BindingSource component.

EsempioExample

Il seguente esempio di codice mostra come associare un controllo DataGridView a un tipo personalizzato usando un componente BindingSource.The following code example demonstrates how to bind a DataGridView control to a custom type by using a BindingSource component. Quando si esegue l'esempio, si noterà che le etichette delle colonne di DataGridView rispecchiano le proprietà di un oggetto Customer, prima ancora che il controllo venga popolato con i dati.When you run the example, you'll notice the DataGridView has labeled columns that reflect the properties of a Customer object, before the control is populated with data. L'esempio contiene un pulsante Add Customer per aggiungere dati al controllo DataGridView.The example has an Add Customer button to add data to the DataGridView control. Quando si fa clic sul pulsante, un nuovo oggetto Customer viene aggiunto a BindingSource.When you click the button, a new Customer object is added to the BindingSource. In uno scenario reale, i dati potrebbero essere ottenuti da una chiamata a un servizio Web o da un'altra origine dati.In a real-world scenario, the data might be obtained by a call to a Web service or other data source.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

class Form1 : Form
{
    BindingSource bSource = new BindingSource();
    private Button button1;
    DataGridView dgv = new DataGridView();

    public Form1()
    {
        this.button1 = new System.Windows.Forms.Button();
        this.button1.Location = new System.Drawing.Point(140, 326);
        this.button1.Name = "button1";
        this.button1.AutoSize = true;
        this.button1.Text = "Add Customer";
        this.button1.Click += new System.EventHandler(this.button1_Click);
        this.ClientSize = new System.Drawing.Size(362, 370);
        this.Controls.Add(this.button1);

        // Bind the BindingSource to the DemoCustomer type.
        bSource.DataSource = typeof(DemoCustomer);

        // Set up the DataGridView control.
        dgv.Dock = DockStyle.Top;
        this.Controls.Add(dgv);

        // Bind the DataGridView control to the BindingSource.
        dgv.DataSource = bSource;
       
    }
    public static void Main()
    {
        Application.Run(new Form1());
     
    }

    private void button1_Click(object sender, EventArgs e)
    {
        bSource.Add(new DemoCustomer(DateTime.Today));
    }
}

// This simple class is used to demonstrate binding to a type.
public class DemoCustomer
{
    public DemoCustomer()
    {
        idValue = Guid.NewGuid();
    }

    public DemoCustomer(DateTime FirstOrderDate)
    {
        FirstOrder = FirstOrderDate;
        idValue = Guid.NewGuid();
    }
    // These fields hold the data that backs the public properties.
    private DateTime firstOrderDateValue;
    private Guid idValue;
    private string custNameValue;

    public string CustomerName
    {
        get { return custNameValue; }
        set { custNameValue = value; }
    }
	
    // This is a property that represents a birth date.
    public DateTime FirstOrder
    {
        get
        {
            return this.firstOrderDateValue;
        }
        set
        {
            if (value != this.firstOrderDateValue)
            {
                this.firstOrderDateValue = value;
            }
        }
    }

    // This is a property that represents a customer ID.
    public Guid ID
    {
        get
        {
            return this.idValue;
        }
    }
}
Imports System
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Data
Imports System.Drawing
Imports System.Windows.Forms

Class Form1
    Inherits Form
    Private bSource As New BindingSource()
    Private WithEvents button1 As Button
    Private dgv As New DataGridView()

    Public Sub New()
        Me.button1 = New System.Windows.Forms.Button()
        Me.button1.Location = New System.Drawing.Point(140, 326)
        Me.button1.Name = "button1"
        Me.button1.AutoSize = True
        Me.button1.Text = "Add Customer"
        Me.ClientSize = New System.Drawing.Size(362, 370)
        Me.Controls.Add(Me.button1)

        ' Bind the BindingSource to the DemoCustomer type.
        bSource.DataSource = GetType(DemoCustomer)

        ' Set up the DataGridView control.
        dgv.Dock = DockStyle.Top
        Me.Controls.Add(dgv)

        ' Bind the DataGridView control to the BindingSource.
        dgv.DataSource = bSource

    End Sub

    Public Shared Sub Main()
        Application.Run(New Form1())

    End Sub

    Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
        Handles button1.Click
        bSource.Add(New DemoCustomer(DateTime.Today))

    End Sub
End Class

' This simple class is used to demonstrate binding to a type.
Public Class DemoCustomer

    Public Sub New()
        idValue = Guid.NewGuid()
    End Sub

    Public Sub New(ByVal FirstOrderDate As DateTime)
        FirstOrder = FirstOrderDate
        idValue = Guid.NewGuid()
    End Sub

    ' These fields hold the data that backs the public properties.
    Private firstOrderDateValue As DateTime
    Private idValue As Guid
    Private custNameValue As String

    Public Property CustomerName() As String
        Get
            Return custNameValue
        End Get
        Set(ByVal value As String)
            custNameValue = value
        End Set
    End Property

    ' This is a property that represents the first order date.
    Public Property FirstOrder() As DateTime
        Get
            Return Me.firstOrderDateValue
        End Get
        Set(ByVal value As DateTime)
            If value <> Me.firstOrderDateValue Then
                Me.firstOrderDateValue = value
            End If
        End Set
    End Property

    ' This is a property that represents a customer ID.
    Public ReadOnly Property ID() As Guid
        Get
            Return Me.idValue
        End Get
    End Property
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

BindingNavigator
DataGridView
BindingSource
Componente BindingSourceBindingSource Component