방법: 동일한 데이터 소스에 바인딩된 여러 컨트롤의 동기화 상태가 유지되도록 설정

Windows Forms에서 데이터 바인딩과 관련된 작업을 수행할 때 여러 컨트롤이 동일한 데이터 소스에 바인딩되어 있는 경우가 종종 있습니다. 경우에 따라 각 컨트롤의 바인딩된 속성이 다른 컨트롤 및 데이터 소스와 동기화 상태를 유지하도록 하기 위해 추가 단계가 필요할 수 있습니다. 이러한 단계는 다음과 같은 두 가지 경우에 필요합니다.

첫 번째의 경우 BindingSource를 사용하여 컨트롤에 데이터 소스를 바인딩할 수 있습니다. 두 번째의 경우에는 BindingSource를 사용하고 BindingComplete 이벤트를 처리한 다음 연관된 BindingManagerBase에서 EndCurrentEdit를 호출합니다.

예제

다음 코드 예제에서는 BindingSource 구성 요소를 사용하여 DataSet의 동일한 열에 세 개의 컨트롤, 즉 텍스트 상자 컨트롤 두 개와 DataGridView 컨트롤 한 개를 바인딩하는 방법을 보여 줍니다. 이 예제에서는 BindingComplete 이벤트를 처리하고, 한 텍스트 상자의 텍스트 값이 변경될 때 다른 텍스트 상자와 DataGridView 컨트롤이 올바른 값으로 업데이트되도록 하는 방법도 보여 줍니다.

이 예제에서는 BindingSource를 사용하여 데이터 소스와 컨트롤을 바인딩합니다. 또는 데이터 소스에 직접 컨트롤을 바인딩하고 폼의 BindingContext에서 바인딩에 대한 BindingManagerBase를 검색한 다음 BindingManagerBaseBindingComplete 이벤트를 처리할 수도 있습니다. 이 작업을 수행하는 방법의 예제는 BindingManagerBaseBindingComplete 이벤트에 대한 도움말 페이지를 참조하십시오.

' Declare the controls to be used.
Private WithEvents bindingSource1 As BindingSource
Private WithEvents textBox1 As TextBox
Private WithEvents textBox2 As TextBox
Private WithEvents dataGridView1 As DataGridView


Private Sub InitializeControlsAndDataSource() 
    ' Initialize the controls and set location, size and 
    ' other basic properties.
    Me.dataGridView1 = New DataGridView()
    Me.bindingSource1 = New BindingSource()
    Me.textBox1 = New TextBox()
    Me.textBox2 = New TextBox()
    Me.dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize
    Me.dataGridView1.Dock = DockStyle.Top
    Me.dataGridView1.Location = New Point(0, 0)
    Me.dataGridView1.Size = New Size(292, 150)
    Me.textBox1.Location = New Point(132, 156)
    Me.textBox1.Size = New Size(100, 20)
    Me.textBox2.Location = New Point(12, 156)
    Me.textBox2.Size = New Size(100, 20)
    Me.ClientSize = New Size(292, 266)
    Me.Controls.Add(Me.textBox2)
    Me.Controls.Add(Me.textBox1)
    Me.Controls.Add(Me.dataGridView1)

    ' Declare the DataSet and add a table and column.
    Dim set1 As New DataSet()
    set1.Tables.Add("Menu")
    set1.Tables(0).Columns.Add("Beverages")

    ' Add some rows to the table.
    set1.Tables(0).Rows.Add("coffee")
    set1.Tables(0).Rows.Add("tea")
    set1.Tables(0).Rows.Add("hot chocolate")
    set1.Tables(0).Rows.Add("milk")
    set1.Tables(0).Rows.Add("orange juice")

    ' Set the data source to the DataSet.
    bindingSource1.DataSource = set1

    'Set the DataMember to the Menu table.
    bindingSource1.DataMember = "Menu"

    ' Add the control data bindings.
    dataGridView1.DataSource = bindingSource1
    textBox1.DataBindings.Add("Text", bindingSource1, "Beverages", _
        True, DataSourceUpdateMode.OnPropertyChanged)
    textBox2.DataBindings.Add("Text", bindingSource1, "Beverages", _
        True, DataSourceUpdateMode.OnPropertyChanged)


End Sub 'InitializeControlsAndDataSource

Private Sub bindingSource1_BindingComplete(ByVal sender As Object, _
    ByVal e As BindingCompleteEventArgs) Handles bindingSource1.BindingComplete

    ' Check if the data source has been updated, and that no error has occured.
    If e.BindingCompleteContext = BindingCompleteContext.DataSourceUpdate _
        AndAlso e.Exception Is Nothing Then

        ' If not, end the current edit.
        e.Binding.BindingManagerBase.EndCurrentEdit()
    End If

End Sub

        // Declare the controls to be used.
        private BindingSource bindingSource1;
        private TextBox textBox1;
        private TextBox textBox2;
        private DataGridView dataGridView1;

        private void InitializeControlsAndDataSource()
        {
            // Initialize the controls and set location, size and 
            // other basic properties.
            this.dataGridView1 = new DataGridView();
            this.bindingSource1 = new BindingSource();
            this.textBox1 = new TextBox();
            this.textBox2 = new TextBox();
            this.dataGridView1.ColumnHeadersHeightSizeMode =
                DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.dataGridView1.Dock = DockStyle.Top;
            this.dataGridView1.Location = new Point(0, 0);
            this.dataGridView1.Size = new Size(292, 150);
            this.textBox1.Location = new Point(132, 156);
            this.textBox1.Size = new Size(100, 20);
            this.textBox2.Location = new Point(12, 156);
            this.textBox2.Size = new Size(100, 20);
            this.ClientSize = new Size(292, 266);
            this.Controls.Add(this.textBox2);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.dataGridView1);

            // Declare the DataSet and add a table and column.
            DataSet set1 = new DataSet();
            set1.Tables.Add("Menu");
            set1.Tables[0].Columns.Add("Beverages");

            // Add some rows to the table.
            set1.Tables[0].Rows.Add("coffee");
            set1.Tables[0].Rows.Add("tea");
            set1.Tables[0].Rows.Add("hot chocolate");
            set1.Tables[0].Rows.Add("milk");
            set1.Tables[0].Rows.Add("orange juice");

            // Set the data source to the DataSet.
            bindingSource1.DataSource = set1;

            //Set the DataMember to the Menu table.
            bindingSource1.DataMember = "Menu";

            // Add the control data bindings.
            dataGridView1.DataSource = bindingSource1;
            textBox1.DataBindings.Add("Text", bindingSource1, 
                "Beverages", true, DataSourceUpdateMode.OnPropertyChanged);
            textBox2.DataBindings.Add("Text", bindingSource1, 
                "Beverages", true, DataSourceUpdateMode.OnPropertyChanged);
            bindingSource1.BindingComplete += 
                new BindingCompleteEventHandler(bindingSource1_BindingComplete);
        }

        private void bindingSource1_BindingComplete(object sender, BindingCompleteEventArgs e)
        {
            // Check if the data source has been updated, and that no error has occured.
            if (e.BindingCompleteContext == 
                BindingCompleteContext.DataSourceUpdate && e.Exception == null)

                // If not, end the current edit.
                e.Binding.BindingManagerBase.EndCurrentEdit();
        }

코드 컴파일

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

  • System, System.Windows.FormsSystem.Drawing 어셈블리에 대한 참조

  • Load 이벤트가 처리된 폼과 해당 폼의 Load 이벤트 처리기에서 예제의 InitializeControlsAndDataSource 메서드를 호출하는 코드

참고 항목

작업

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

개념

Windows Forms 데이터 바인딩의 변경 알림

데이터 바인딩과 관련된 인터페이스

기타 리소스

Windows Forms 데이터 바인딩