방법: BindingSource 구성 요소를 사용하여 폼 간에 바인딩된 데이터 공유

BindingSource 구성 요소를 사용하여 여러 폼 간에 데이터를 쉽게 공유할 수 있습니다. 예를 들어, 데이터 소스의 데이터를 요약하는 읽기 전용 폼 하나와 데이터 소스에서 현재 선택된 항목에 대한 세부 정보가 포함된 편집 가능한 다른 폼을 표시할 수 있습니다. 다음 예제에서는 이러한 경우를 보여 줍니다.

예제

다음 코드 예제에서는 BindingSource와 폼 간에 바인딩된 데이터를 공유하는 방법을 보여 줍니다. 이 예제에서는 공유된 BindingSource가 자식 폼의 생성자에 전달됩니다. 사용자는 자식 폼을 사용하여 기본 폼에서 현재 선택된 항목의 데이터를 편집할 수 있습니다.

참고

이 예제에서는 BindingSource 구성 요소의 BindingComplete 이벤트를 처리하여 두 폼의 동기화 상태가 유지되도록 합니다. 이렇게 해야 하는 이유에 대한 자세한 내용은 방법: 동일한 데이터 소스에 바인딩된 여러 컨트롤의 동기화 상태가 유지되도록 설정을 참조하십시오.

Imports System
Imports System.Drawing
Imports System.Windows.Forms
Imports System.Data

Public Class MainForm
    Inherits Form

    Public Sub New()
    End Sub

    Private WithEvents bindingSource1 As BindingSource
    Private WithEvents button1 As Button

    Private Sub MainForm_Load(ByVal sender As Object, ByVal e As EventArgs) _
        Handles Me.Load

        InitializeData()
    End Sub


    Private Sub InitializeData()
        bindingSource1 = New System.Windows.Forms.BindingSource()
        Dim dataset1 As New DataSet()
        ClientSize = New System.Drawing.Size(292, 266)

        ' Some xml data to populate the DataSet with.
        ' Some xml data to populate the DataSet with.
        Dim musicXml As String = "<?xml version='1.0' encoding='UTF-8'?>" & _
            "<music><recording><artist>Dave Matthews</artist>" & _
            "<cd>Under the Table and Dreaming</cd>" & _
            "<releaseDate>1994</releaseDate><rating>3.5</rating></recording>" & _
            "<recording><artist>Coldplay</artist><cd>X&amp;Y</cd>" & _
            "<releaseDate>2005</releaseDate><rating>4</rating></recording>" & _
            "<recording><artist>Dave Matthews</artist>" & _
            "<cd>Live at Red Rocks</cd>" & _
            "<releaseDate>1997</releaseDate><rating>4</rating></recording>" & _
            "<recording><artist>U2</artist>" & _
            "<cd>Joshua Tree</cd><releaseDate>1987</releaseDate>" & _
            "<rating>5</rating></recording>" & _
            "<recording><artist>U2</artist>" & _
            "<cd>How to Dismantle an Atomic Bomb</cd>" & _
            "<releaseDate>2004</releaseDate><rating>4.5</rating></recording>" & _
            "<recording><artist>Natalie Merchant</artist>" & _
            "<cd>Tigerlily</cd><releaseDate>1995</releaseDate>" & _
            "<rating>3.5</rating></recording>" & _
            "</music>"

        ' Read the xml.
        Dim reader As New System.IO.StringReader(musicXml)
        dataset1.ReadXml(reader)

        ' Get a DataView of the table contained in the dataset.
        Dim tables As DataTableCollection = dataset1.Tables
        Dim view1 As New DataView(tables(0))

        ' Create a DataGridView control and add it to the form.
        Dim datagridview1 As New DataGridView()
        datagridview1.ReadOnly = True
        datagridview1.AutoGenerateColumns = True
        datagridview1.Width = 300
        Me.Controls.Add(datagridview1)
        bindingSource1.DataSource = view1
        datagridview1.DataSource = bindingSource1
        datagridview1.Columns.Remove("artist")
        datagridview1.Columns.Remove("releaseDate")

        ' Create and add a button to the form. 
        button1 = New Button()
        button1.AutoSize = True
        button1.Text = "Show/Edit Details"
        Me.Controls.Add(button1)
        button1.Location = New Point(50, 200)

    End Sub

    ' Handle the BindingComplete event to ensure the two forms
    ' remain synchronized.
    Private Sub bindingSource1_BindingComplete(ByVal sender As Object, _
        ByVal e As BindingCompleteEventArgs) Handles bindingSource1.BindingComplete
        If e.BindingCompleteContext = BindingCompleteContext.DataSourceUpdate _
            AndAlso e.Exception Is Nothing Then
            e.Binding.BindingManagerBase.EndCurrentEdit()
        End If

    End Sub

    ' The detailed form will be shown when the button is clicked.
    Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
        Handles button1.Click

        Dim detailForm As New DetailForm(bindingSource1)
        detailForm.Show()
    End Sub


    <STAThread()> _
    Shared Sub Main()
        Application.EnableVisualStyles()
        Application.Run(New MainForm())

    End Sub
End Class

' The detail form class. 
Public Class DetailForm
    Inherits Form
    Private formDataSource As BindingSource

    ' The constructor takes a BindingSource object.
    Public Sub New(ByVal dataSource As BindingSource)
        formDataSource = dataSource
        Me.ClientSize = New Size(240, 200)
        Dim textBox1 As New TextBox()
        Me.Text = "Selection Details"
        textBox1.Width = 220
        Dim textBox2 As New TextBox()
        Dim textBox3 As New TextBox()
        Dim textBox4 As New TextBox()
        textBox4.Width = 30
        textBox3.Width = 50

        ' Associate each text box with a column from the data source.
        textBox1.DataBindings.Add("Text", formDataSource, "cd", _
            True, DataSourceUpdateMode.OnPropertyChanged)

        textBox2.DataBindings.Add("Text", formDataSource, "artist", True)
        textBox3.DataBindings.Add("Text", formDataSource, "releaseDate", True)
        textBox4.DataBindings.Add("Text", formDataSource, "rating", True)
        textBox1.Location = New Point(10, 10)
        textBox2.Location = New Point(10, 40)
        textBox3.Location = New Point(10, 80)
        textBox4.Location = New Point(10, 120)
        Me.Controls.AddRange(New Control() {textBox1, textBox2, textBox3, _
            textBox4})

    End Sub
End Class
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Data;

namespace BindingSourceMultipleForms
{
    public class MainForm : Form
    {
        public MainForm()
        {
            this.Load += new EventHandler(MainForm_Load);
        }

        private BindingSource bindingSource1;
        private Button button1;

        private void MainForm_Load(object sender, EventArgs e)
        {
            InitializeData();
        }

        private void InitializeData()
        {
            bindingSource1 = new System.Windows.Forms.BindingSource();

            // Handle the BindingComplete event to ensure the two forms
            // remain synchronized.
            bindingSource1.BindingComplete +=  
                new BindingCompleteEventHandler(bindingSource1_BindingComplete);
            ClientSize = new System.Drawing.Size(292, 266);
            DataSet dataset1 = new DataSet();

            // Some xml data to populate the DataSet with.
            string musicXml =
                "<?xml version='1.0' encoding='UTF-8'?>" +
                "<music>" +
                 "<recording><artist>Dave Matthews</artist>" +
                 "<cd>Under the Table and Dreaming</cd>" + 
                 "<releaseDate>1994</releaseDate><rating>3.5</rating></recording>" +
                 "<recording><artist>Coldplay</artist><cd>X&amp;Y</cd>" + 
                 "<releaseDate>2005</releaseDate><rating>4</rating></recording>" +
                 "<recording><artist>Dave Matthews</artist>" + 
                 "<cd>Live at Red Rocks</cd>" + 
                 "<releaseDate>1997</releaseDate><rating>4</rating></recording>" +
                 "<recording><artist>U2</artist>" + 
                 "<cd>Joshua Tree</cd><releaseDate>1987</releaseDate>" + 
                 "<rating>5</rating></recording>" +
                 "<recording><artist>U2</artist>" +
                 "<cd>How to Dismantle an Atomic Bomb</cd>" + 
                 "<releaseDate>2004</releaseDate><rating>4.5</rating></recording>" +
                 "<recording><artist>Natalie Merchant</artist>" +
                 "<cd>Tigerlily</cd><releaseDate>1995</releaseDate>" +
                 "<rating>3.5</rating></recording>" +
                 "</music>";

            // Read the xml.
            System.IO.StringReader reader = new System.IO.StringReader(musicXml);
            dataset1.ReadXml(reader); 

            // Get a DataView of the table contained in the dataset.
            DataTableCollection tables = dataset1.Tables;
            DataView view1 = new DataView(tables[0]);

            // Create a DataGridView control and add it to the form.
            DataGridView datagridview1 = new DataGridView();
            datagridview1.ReadOnly = true;
            datagridview1.AutoGenerateColumns = true;
            datagridview1.Width = 300;
            this.Controls.Add(datagridview1);
            bindingSource1.DataSource = view1;
            datagridview1.DataSource = bindingSource1;
            datagridview1.Columns.Remove("artist");
            datagridview1.Columns.Remove("releaseDate");

            // Create and add a button to the form. 
            button1 = new Button();
            button1.AutoSize = true;
            button1.Text = "Show/Edit Details";
            this.Controls.Add(button1);
            button1.Location = new Point(50, 200);
            button1.Click += new EventHandler(button1_Click);
        }

        // Handle the BindingComplete event to ensure the two forms
        // remain synchronized.
        private void bindingSource1_BindingComplete(object sender, BindingCompleteEventArgs e)
        {
            if (e.BindingCompleteContext == BindingCompleteContext.DataSourceUpdate
                && e.Exception == null)
                e.Binding.BindingManagerBase.EndCurrentEdit();
        }

        // The detailed form will be shown when the button is clicked.
        private void button1_Click(object sender, EventArgs e)
        {
            DetailForm detailForm = new DetailForm(bindingSource1);
            detailForm.Show();
        }

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.Run(new MainForm());
        }
    }

    // The detail form class. 
    public class DetailForm : Form
    {
        private BindingSource formDataSource;

        // The constructor takes a BindingSource object.
        public DetailForm(BindingSource dataSource)
        {
            formDataSource = dataSource;
            this.ClientSize = new Size(240, 200);
            TextBox textBox1 = new TextBox();
            this.Text = "Selection Details";
            textBox1.Width = 220;
            TextBox textBox2 = new TextBox();
            TextBox textBox3 = new TextBox();
            TextBox textBox4 = new TextBox();
            textBox4.Width = 30;
            textBox3.Width = 50;

            // Associate each text box with a column from the data source.
            textBox1.DataBindings.Add("Text", formDataSource, "cd", true, DataSourceUpdateMode.OnPropertyChanged);

            textBox2.DataBindings.Add("Text", formDataSource, "artist", true);
            textBox3.DataBindings.Add("Text", formDataSource, "releaseDate", true);
            textBox4.DataBindings.Add("Text", formDataSource, "rating", true);
            textBox1.Location = new Point(10, 10);
            textBox2.Location = new Point(10, 40);
            textBox3.Location = new Point(10, 80);
            textBox4.Location = new Point(10, 120);
            this.Controls.AddRange(new Control[] { textBox1, textBox2, textBox3, textBox4 });
        }

    }
}

코드 컴파일

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

  • System, System.Windows.Forms, System.Drawing, System.Data 및 System.Xml 어셈블리에 대한 참조

Visual Basic 또는 Visual C#의 명령줄에서 이 예제를 빌드하는 방법에 대한 자세한 내용은 명령줄에서 빌드(Visual Basic) 또는 csc.exe를 사용한 명령줄 빌드를 참조하십시오. Visual Studio에서 코드를 새 프로젝트에 붙여넣어 이 예제를 빌드할 수도 있습니다. 자세한 내용은 다음을 참조하십시오. 방법: Visual Studio를 사용하여 전체 Windows Forms 코드 예제 컴파일 및 실행방법: Visual Studio를 사용하여 전체 Windows Forms 코드 예제 컴파일 및 실행방법: Visual Studio를 사용하여 전체 Windows Forms 코드 예제 컴파일 및 실행방법: Visual Studio를 사용하여 전체 Windows Forms 코드 예제 컴파일 및 실행방법: Visual Studio를 사용하여 전체 Windows Forms 코드 예제 컴파일 및 실행.

참고 항목

작업

방법: 데이터 바인딩에서 발생하는 오류 및 예외 처리

기타 리소스

BindingSource 구성 요소

Windows Forms 데이터 바인딩