Cómo: Garantizar que varios controles enlazados al mismo origen de datos permanezcan sincronizados

A menudo, al trabajar con el enlace de datos en formularios Windows Forms, se enlazan varios controles al mismo origen de datos. En algunos casos, puede ser necesario adoptar medidas adicionales para garantizar que las propiedades enlazadas de los controles permanezcan sincronizadas entre sí y con el origen de datos. Estas medidas son necesarias en dos situaciones:

En el primer caso, puede utilizar un objeto BindingSource para enlazar el origen de datos a los controles. En el segundo caso, se utiliza un objeto BindingSource, se controla el evento BindingComplete y se llama al método EndCurrentEdit en el objeto BindingManagerBase asociado.

Ejemplo

En el ejemplo de código siguiente se muestra cómo enlazar tres controles (dos controles de cuadro de texto y un control DataGridView) a la misma columna de un DataSet mediante un componente BindingSource. En este ejemplo se muestra cómo controlar el evento BindingComplete y garantizar que, cuando cambie el valor de texto de uno de los cuadros de texto, se actualicen con el valor correcto el otro cuadro de texto y el control DataGridView.

En el ejemplo se utiliza un BindingSource para enlazar el origen de datos y los controles. Asimismo, se puede enlazar directamente los controles al origen de datos y recuperar un objeto BindingManagerBase para el enlace del BindingContext del formulario y, a continuación, controlar el evento BindingComplete correspondiente al objeto BindingManagerBase. Para obtener un ejemplo de cómo hacerlo, vea la página de Ayuda correspondiente al evento BindingComplete de BindingManagerBase.

' 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();
        }

Compilar el código

  • Este ejemplo de código requiere

  • Referencias a los ensamblados System, System.Windows.Forms y System.Drawing.

  • Un formulario con el evento Load controlado y una llamada al método InitializeControlsAndDataSource en el ejemplo del controlador de eventos Load del formulario.

Vea también

Tareas

Cómo: Compartir datos enlazados entre formularios mediante el componente BindingSource

Conceptos

Notificación de cambios en el enlace de datos de Windows Forms

Interfaces relacionadas con el enlace de datos

Otros recursos

Enlace de datos en Windows Forms