Cómo: Reflejar las actualizaciones de los orígenes de datos en un control de Windows Forms con BindingSource

Actualización: noviembre 2007

Cuando utilice controles enlazados a datos, a veces tendrá que responder a los cambios del origen de datos cuando el origen de datos no provoque eventos cambiados en la lista. Cuando utiliza el componente BindingSource para enlazar el origen de datos a un control de formularios Windows Forms, se puede notificar al control que el origen de datos ha cambiado llamando al método ResetBindings.

Ejemplo

El ejemplo de código siguiente muestra cómo utilizar el método ResetBindings para notificar a un control enlazado que se ha producido una actualización en el origen de datos.

Imports System
Imports System.ComponentModel
Imports System.Drawing
Imports System.Text
Imports System.Windows.Forms
Imports System.Collections


Class Form1
    Inherits Form

    ' Declare the objects on the form.
    Private label1 As Label
    Private label2 As Label
    Private textBox1 As TextBox
    Private textBox2 As TextBox
    Private WithEvents button1 As Button
    Private bindingSource1 As BindingSource
    Private states As ArrayList

    Public Sub New()

        ' Basic form setup.
        Me.button1 = New System.Windows.Forms.Button()
        Me.textBox1 = New System.Windows.Forms.TextBox()
        Me.label1 = New System.Windows.Forms.Label()
        Me.label2 = New System.Windows.Forms.Label()
        Me.textBox2 = New System.Windows.Forms.TextBox()
        Me.button1.Location = New System.Drawing.Point(12, 18)
        Me.button1.Size = New System.Drawing.Size(119, 38)
        Me.button1.Text = "RemoveAt(0)"
        Me.textBox1.Location = New System.Drawing.Point(55, 75)
        Me.textBox1.ReadOnly = True
        Me.textBox1.Size = New System.Drawing.Size(119, 20)
        Me.label1.Location = New System.Drawing.Point(12, 110)
        Me.label1.Size = New System.Drawing.Size(43, 14)
        Me.label1.Text = "Capital:"
        Me.label2.Location = New System.Drawing.Point(12, 78)
        Me.label2.Size = New System.Drawing.Size(34, 14)
        Me.label2.Text = "State:"
        Me.textBox2.Location = New System.Drawing.Point(55, 110)
        Me.textBox2.Size = New System.Drawing.Size(119, 20)
        Me.textBox2.ReadOnly = True
        Me.ClientSize = New System.Drawing.Size(292, 273)
        Me.Controls.Add(Me.textBox2)
        Me.Controls.Add(Me.label2)
        Me.Controls.Add(Me.label1)
        Me.Controls.Add(Me.textBox1)
        Me.Controls.Add(Me.button1)
        Me.Text = "Form1"

        ' Create an ArrayList containing some of the State objects.
        states = New ArrayList()
        states.Add(New State("California", "Sacramento"))
        states.Add(New State("Oregon", "Salem"))
        states.Add(New State("Washington", "Olympia"))
        states.Add(New State("Idaho", "Boise"))
        states.Add(New State("Utah", "Salt Lake City"))
        states.Add(New State("Hawaii", "Honolulu"))
        states.Add(New State("Colorado", "Denver"))
        states.Add(New State("Montana", "Helena"))

        bindingSource1 = New BindingSource()

        ' Bind BindingSource1 to the list of states.
        bindingSource1.DataSource = states

        ' Bind the two text boxes to properties of State.
        textBox1.DataBindings.Add("Text", bindingSource1, "Name")
        textBox2.DataBindings.Add("Text", bindingSource1, "Capital")

    End Sub

    Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
        Handles button1.Click

        ' If items remain in the list, remove the first item. 
        If states.Count > 0 Then
            states.RemoveAt(0)

            ' Call ResetBindings to update the textboxes.
            bindingSource1.ResetBindings(False)
        End If

    End Sub 'button1_Click

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

    End Sub

    ' The State class to add to the ArrayList.
    Private Class State
        Private stateName As String

        Public ReadOnly Property Name() As String
            Get
                Return stateName
            End Get
        End Property

        Private stateCapital As String

        Public ReadOnly Property Capital() As String
            Get
                Return stateCapital
            End Get
        End Property

        Public Sub New(ByVal name As String, ByVal capital As String)
            stateName = name
            stateCapital = capital

        End Sub
    End Class
End Class
using System;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;


namespace System_Windows_Forms_UpdateBinding
{
    class Form1 : Form
    {
        // Declare the objects on the form.
        private Label label1;
        private Label label2;
        private TextBox textBox1;
        private TextBox textBox2;
        private Button button1;
        private BindingSource bindingSource1;
        ArrayList states;

        public Form1()
        {
            // Basic form setup.
            this.button1 = new System.Windows.Forms.Button();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.textBox2 = new System.Windows.Forms.TextBox();
            this.button1.Location = new System.Drawing.Point(12, 18);
            this.button1.Size = new System.Drawing.Size(119, 38);
            this.button1.Text = "RemoveAt(0)";
            this.button1.Click += new System.EventHandler(this.button1_Click);
            this.textBox1.Location = new System.Drawing.Point(55, 75);
            this.textBox1.ReadOnly = true;
            this.textBox1.Size = new System.Drawing.Size(119, 20);
            this.label1.Location = new System.Drawing.Point(12, 110);
            this.label1.Size = new System.Drawing.Size(43, 14);
            this.label1.Text = "Capital:";
            this.label2.Location = new System.Drawing.Point(12, 78);
            this.label2.Size = new System.Drawing.Size(34, 14);
            this.label2.Text = "State:";
            this.textBox2.Location = new System.Drawing.Point(55, 110);
            this.textBox2.Size = new System.Drawing.Size(119, 20);
            this.textBox2.ReadOnly = true;
            this.ClientSize = new System.Drawing.Size(292, 273);
            this.Controls.Add(this.textBox2);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.button1);
            this.Text = "Form1";

            // Create an ArrayList containing some of the State objects.
            states = new ArrayList();
            states.Add(new State("California", "Sacramento"));
            states.Add(new State("Oregon", "Salem"));
            states.Add(new State("Washington", "Olympia"));
            states.Add(new State("Idaho", "Boise"));
            states.Add(new State("Utah", "Salt Lake City"));
            states.Add(new State("Hawaii", "Honolulu"));
            states.Add(new State("Colorado", "Denver"));
            states.Add(new State("Montana", "Helena"));

            bindingSource1 = new BindingSource();

            // Bind BindingSource1 to the list of states.
            bindingSource1.DataSource = states;

            // Bind the two text boxes to properties of State.
            textBox1.DataBindings.Add("Text", bindingSource1, "Name");
            textBox2.DataBindings.Add("Text", bindingSource1, "Capital");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // If items remain in the list, remove the first item. 
            if (states.Count > 0)
            {
                states.RemoveAt(0);

                // Call ResetBindings to update the textboxes.
                bindingSource1.ResetBindings(false);
            }
        }

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

        }

        // The State class to add to the ArrayList.
        private class State
        {
            private string stateName;
            public string Name 
            {
                get {return stateName;}
            }

            private string stateCapital;
            public string Capital 
            {
                get {return stateCapital;}
            }

            public State ( string name, string capital)
            {
                stateName = name;
                stateCapital = capital;
            }
        }

    }
}
#using <System.Xml.dll>
#using <System.dll>
#using <System.Data.dll>
#using <System.Drawing.dll>
#using <System.Windows.Forms.dll>

using namespace System;
using namespace System::Collections::Generic;
using namespace System::ComponentModel;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::Text;
using namespace System::Xml;
using namespace System::Windows::Forms;
using namespace System::IO;

namespace System_Windows_Forms_UpdateBinding
{
   public ref class Form1: public Form
   {
   public:
      Form1()
      {
         InitializeComponent();
      }

      [STAThread]
      static void Main()
      {
         Application::EnableVisualStyles();
         Application::Run( gcnew Form1 );
      }

   private:
      void Form1_Load( System::Object^ /*sender*/, System::EventArgs^ /*e*/ )
      {
         // The xml to bind to.
         String^ xml = "<US><states>" +
            "<state><name>Washington</name><capital>Olympia</capital></state>" +
            "<state><name>Oregon</name><capital>Salem</capital></state>" +
            "<state><name>California</name><capital>Sacramento</capital></state>" +
            "<state><name>Nevada</name><capital>Carson City</capital></state>" +
            "</states></US>";

         // Convert the xml string to bytes and load into a memory stream.
         array<Byte>^ xmlBytes = Encoding::UTF8->GetBytes( xml );
         MemoryStream^ stream = gcnew MemoryStream( xmlBytes,false );

         // Create a DataSet and load the xml into it.
         dataSet1->ReadXml( stream );

         // Set the DataSource to the DataSet, and the DataMember
         // to state.
         bindingSource1->DataSource = dataSet1;
         bindingSource1->DataMember = "state";

         dataGridView1->DataSource = bindingSource1;
      }

   private:
      void button1_Click( Object^ /*sender*/, EventArgs^ /*e*/ )
      {
         String^ xml = "<US><states>"
            + "<state><name>Washington</name><capital>Olympia</capital> "
            + "<flower>Coast Rhododendron</flower></state>"
            + "<state><name>Oregon</name><capital>Salem</capital>"
            + "<flower>Oregon Grape</flower></state>"
            + "<state><name>California</name><capital>Sacramento</capital>"
            + "<flower>California Poppy</flower></state>"
            + "<state><name>Nevada</name><capital>Carson City</capital>"
            + "<flower>Sagebrush</flower></state>"
            + "</states></US>";

         // Convert the xml string to bytes and load into a memory stream.
         array<Byte>^ xmlBytes = Encoding::UTF8->GetBytes( xml );
         MemoryStream^ stream = gcnew MemoryStream( xmlBytes,false );

         // Create a DataSet and load the xml into it.
         dataSet2->ReadXml( stream );

         // Set the data source.
         bindingSource1->DataSource = dataSet2;
         bindingSource1->ResetBindings( true );
      }

      System::Windows::Forms::Button^ button1;
      System::Windows::Forms::DataGridView^ dataGridView1;
      System::Windows::Forms::BindingSource^ bindingSource1;
      System::Data::DataSet^ dataSet1;
      DataSet^ dataSet2;

      #pragma region Windows Form Designer generated code 

      /// <summary>
      /// Required method for Designer support - do not modify
      /// the contents of this method with the code editor.
      /// </summary>
      void InitializeComponent()
      {
         this->button1 = gcnew System::Windows::Forms::Button;
         this->dataGridView1 = gcnew System::Windows::Forms::DataGridView;
         this->bindingSource1 = gcnew System::Windows::Forms::BindingSource;
         this->dataSet1 = gcnew System::Data::DataSet;
         this->dataSet2 = gcnew System::Data::DataSet;
         ( (System::ComponentModel::ISupportInitialize^)(this->dataGridView1) )->BeginInit();
         ( (System::ComponentModel::ISupportInitialize^)(this->bindingSource1) )->BeginInit();
         ( (System::ComponentModel::ISupportInitialize^)(this->dataSet1) )->BeginInit();
         ( (System::ComponentModel::ISupportInitialize^)(this->dataSet2) )->BeginInit();
         this->SuspendLayout();

         //
         // button1
         //
         this->button1->Location = System::Drawing::Point( 98, 222 );
         this->button1->Name = "button1";
         this->button1->TabIndex = 0;
         this->button1->Text = "button1";
         this->button1->Click += gcnew System::EventHandler( this, &Form1::button1_Click );

         //
         // dataGridView1
         //
         this->dataGridView1->Dock = System::Windows::Forms::DockStyle::Top;
         this->dataGridView1->Location = System::Drawing::Point( 0, 0 );
         this->dataGridView1->Name = "dataGridView1";
         this->dataGridView1->Size = System::Drawing::Size( 292, 150 );
         this->dataGridView1->TabIndex = 1;

         //
         // dataSet1
         //
         this->dataSet1->DataSetName = "NewDataSet";
         this->dataSet1->Locale = gcnew System::Globalization::CultureInfo( "en-US" );

         //
         // dataSet2
         //
         this->dataSet2->DataSetName = "NewDataSet";
         this->dataSet2->Locale = gcnew System::Globalization::CultureInfo( "en-US" );

         //
         // Form1
         //
         this->ClientSize = System::Drawing::Size( 292, 273 );
         this->Controls->Add( this->dataGridView1 );
         this->Controls->Add( this->button1 );
         this->Name = "Form1";
         this->Text = "Form1";
         this->Load += gcnew EventHandler( this, &Form1::Form1_Load );
         ( (System::ComponentModel::ISupportInitialize^)(this->dataGridView1) )->EndInit();
         ( (System::ComponentModel::ISupportInitialize^)(this->bindingSource1) )->EndInit();
         ( (System::ComponentModel::ISupportInitialize^)(this->dataSet1) )->EndInit();
         ( (System::ComponentModel::ISupportInitialize^)(this->dataSet2) )->EndInit();
         this->ResumeLayout( false );
      }
      #pragma endregion 
   };
}

int main()
{
   System_Windows_Forms_UpdateBinding::Form1::Main();
}
import System.*;
import System.Collections.Generic.*;
import System.ComponentModel.*;
import System.Data.*;
import System.Data.Common.*;
import System.Diagnostics.*;
import System.Drawing.*;
import System.Data.SqlClient.*;
import System.Windows.Forms.*;

// This demonstrates using a BindingSource component to update
// the schema of a result set from a database query.
public class Form1 extends System.Windows.Forms.Form
{
    // Clicking this button causes a new column to be added to the
    // result set.
    private Button addNewColumnBtn = new Button();

    // This DataGridView control displays the result set data.
    private DataGridView customersDataGridView = new DataGridView();

    // This BindingSource component binds the DataGridView to the
    // result set.
    private BindingSource customersBindingSource = new BindingSource();

    // This counter will be used to name new columns uniquely.
    private int newColumnCount = 0;

    public Form1()
    {
        // Set up the form.
        this.set_Size(new Size(800, 800));
        this.add_Load(new EventHandler(Form1_Load));
        // Set up the "Add New Column" button.
        this.addNewColumnBtn.set_Text("Add New Column");
        this.addNewColumnBtn.set_Dock(DockStyle.Bottom);
        this.addNewColumnBtn.add_Click(new EventHandler(addNewColumnBtn_Click));
        this.get_Controls().Add(this.addNewColumnBtn);
        // Set up the DataGridView control.
        customersDataGridView.set_Dock(DockStyle.Top);
        this.get_Controls().Add(customersDataGridView);
    } //Form1

    private void Form1_Load(Object sender, EventArgs e)
    {
        // Open a connection to the database.
        String connectString = "Integrated Security=SSPI;"
            + "Persist Security Info=False;" 
            + "Initial Catalog=Northwind;Data Source=localhost";
        SqlConnection connection = new SqlConnection();
        connection.set_ConnectionString(connectString);
        connection.Open();
        // Execute the query.
        SqlDataAdapter adapter = new SqlDataAdapter(
            "Select * From Customers", connection);
        DataTable table = new DataTable();
        adapter.Fill(table);
        // Attach the data source to the BindingSource control.
        this.customersBindingSource.set_DataSource(table);
        // Handle the ListChanged event.
        this.customersBindingSource.add_ListChanged(
            new ListChangedEventHandler(customersBindingSource_ListChanged));
        // Attach the BindingSource to the DataGridView.
        this.customersDataGridView.set_DataSource(this.customersBindingSource);
    } //Form1_Load

    // This event handler adds a new column to the result set
    // and calls the ResetBindings method to tell the BindingSource 
    // component that the schema of the result set has changed.
    private void addNewColumnBtn_Click(Object sender, EventArgs e)
    {
        // Increment the new column counter.
        (this.newColumnCount)++;
        // Add a new column to the result set.
        DataTable table = (DataTable)this.customersBindingSource.
            get_DataSource();
        table.get_Columns().Add("NewColumn" + System.Convert.ToString(
            this.newColumnCount), DataColumn.class.ToType());
        // Tell the BindingSource component that the schema of 
        // the result set has changed.
        this.customersBindingSource.ResetBindings(true);
    } //addNewColumnBtn_Click

    // This event handler is used to report changes to the 
    // BindingSource component's underlying list.
    private void customersBindingSource_ListChanged(Object sender, ListChangedEventArgs e)
    {
        Trace.WriteLine(e.get_ListChangedType().ToString());
    } //customersBindingSource_ListChanged

    /** @attribute STAThread()
     */
    public static void main(String[] args)
    {
        Application.EnableVisualStyles();
        Application.Run(new Form1());
    } //main
} //Form1

Compilar el código

Este ejemplo requiere:

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

Para obtener información sobre la generación de este ejemplo desde la línea de comandos de Visual Basic o Visual C#, vea Generar desde la línea de comandos (Visual Basic) o Generar la línea de comandos con csc.exe. También puede generar este ejemplo en Visual Studio pegando el código en un proyecto nuevo.

Vea también

Tareas

Cómo: Enlazar un control de Windows Forms a un tipo

Referencia

BindingNavigator

DataGridView

BindingSource

Otros recursos

BindingSource (Componente)