共用方式為


HOW TO:使用 BindingSource 反映 Windows Form 控制項中的資料來源更新

更新:2007 年 11 月

使用資料繫結控制項時,如果資料來源未引發清單變更事件,有時候必須回應資料來源中的變更。當使用 BindingSource 元件將資料來源繫結至 Windows Form 控制項時,可藉由呼叫 ResetBindings 方法來告知控制項資料來源已變更。

範例

下列程式碼範例示範使用 ResetBindings 方法來告知繫結控制項 (Bound Control) 關於資料來源中的更新。

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

編譯程式碼

這個範例需要:

  • System、System.Drawing 和 System.Windows.Forms 組件的參考。

如需從 Visual Basic 或 Visual C# 的命令列建置這個範例的詳細資訊,請參閱從命令列建置 (Visual Basic)使用 csc.exe 建置命令列。您也可以透過將程式碼貼入新的專案,在 Visual Studio 中建置此範例。

請參閱

工作

HOW TO:將 Windows Form 控制項繫結至型別

參考

BindingNavigator

DataGridView

BindingSource

其他資源

BindingSource 元件