Procedura: garantire la sincronizzazione di più controlli associati alla stessa origine dati

Aggiornamento: novembre 2007

Spesso quando si utilizza l'associazione dati in Windows Form, più controlli vengono associati alla stessa origine dati. In alcuni casi, può essere necessario eseguire altri passaggi per assicurarsi che le proprietà associate dei controlli rimangano sincronizzate tra loro e con l'origine dati. Questi passaggi sono necessari in due situazioni:

Nel primo caso, è possibile utilizzare un componente BindingSource per associare l'origine dati ai controlli. Nel secondo caso, utilizzare un componente BindingSource, gestire l'evento BindingComplete ed eseguire una chiamata al metodo EndCurrentEdit sul controllo BindingManagerBase associato.

Esempio

Nell'esempio di codice seguente viene illustrato come associare tre controlli, ossia due controlli casella di testo e un controllo DataGridView, alla stessa colonna di un controllo DataSet utilizzando un componente BindingSource. Viene descritto come gestire l'evento BindingComplete e assicurarsi che, quando il valore di testo di una delle caselle di testo viene modificato, l'altra casella di testo e il controllo DataGridView vengano aggiornati con il valore corretto.

Nell'esempio si utilizza un componente BindingSource per associare l'origine dati e i controlli. In alternativa, è possibile associare i controlli direttamente all'origine dati e recuperare il componente BindingManagerBase per l'associazione dalla proprietà BindingContext del form, quindi gestire l'evento BindingComplete per BindingManagerBase. Per un esempio di come eseguire questa operazione, vedere la pagina Guida sull'evento BindingComplete di 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();
}

Compilazione del codice

  • Per questo esempio di codice sono necessari i seguenti requisiti

  • Riferimenti agli assembly System, System.Windows.Forms e System.Drawing.

  • Un form con l'evento Load gestito e una chiamata al metodo InitializeControlsAndDataSource nell'esempio dal gestore eventi Load del form.

Vedere anche

Attività

Procedura: condividere dati associati tra form tramite il componente BindingSource

Concetti

Notifica delle modifiche nell'associazione dati dei Windows Form

Interfacce correlate all'associazione dati

Altre risorse

Associazione ai dati di Windows Form