방법: 형식에 Windows Forms 컨트롤 바인딩

데이터와 상호 작용하는 컨트롤을 빌드하는 경우 때로는 개체가 아니라 형식에 컨트롤을 바인딩할 필요가 있습니다. 이 상황은 특히 데이터를 사용할 수 없지만 데이터 바인딩된 컨트롤이 여전히 형식의 공용 인터페이스에서 가져온 정보를 표시해야 하는 경우 디자인 타임에 발생합니다. 예를 들어 웹 서비스에서 노출된 개체에 DataGridView 컨트롤을 바인딩하고 디자인 타임에 DataGridView 컨트롤이 사용자 지정 형식의 멤버 이름으로 해당 열의 레이블을 지정하도록 할 수 있습니다.

BindingSource 구성 요소를 사용하여 컨트롤을 형식에 쉽게 바인딩할 수 있습니다.

예제

다음 코드 예제에서는 BindingSource 구성 요소를 사용하여 DataGridView 컨트롤을 사용자 지정 형식에 바인딩하는 방법을 보여 줍니다. 예제를 실행하면 컨트롤에 데이터가 채워지기 전에 DataGridViewCustomer 개체의 속성을 반영하는 레이블 열이 포함됩니다. 예제에는 DataGridView 컨트롤에 데이터를 추가하는 Add Customer 단추가 있습니다. 이 단추를 클릭하면 새로운 Customer 개체가 BindingSource에 추가됩니다. 실제 시나리오에서는 웹 서비스 또는 다른 데이터 소스를 호출하여 데이터를 가져올 수 있습니다.

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.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

코드 컴파일

이 예제에는 다음 사항이 필요합니다.

  • System 및 System.Windows.Forms 어셈블리에 대한 참조

참고 항목