共用方式為


HOW TO:使用 BindingSource 元件跨表單共用繫結資料

您可以使用 BindingSource 元件,輕鬆地跨表單共用資料。 例如,您可能想要顯示一個唯讀表單,以摘要資料來源的資料,以及另一個可編輯的表單,以包含目前在資料來源中所選取之項目的詳細資料。 這個範例將示範此案例。

範例

下列程式碼範例將示範如何跨表單共用 BindingSource 及其繫結的資料。 在這個範例中,共用的 BindingSource 會傳遞給子表單的建構函式 (Constructor)。 這個子表單可以讓使用者編輯目前在主表單中所選取之項目的資料。

注意事項注意事項

在這個範例中,將處理 BindingSource 元件的 BindingComplete 事件,以確保兩個表單維持同步。 如需為何執行這個處理的詳細資訊,請參閱 HOW TO:確保繫結至相同資料來源的多個控制項都能保持同步

Imports System
Imports System.Drawing
Imports System.Windows.Forms
Imports System.Data

Public Class MainForm
    Inherits Form

    Public Sub New()
    End Sub

    Private WithEvents bindingSource1 As BindingSource
    Private WithEvents button1 As Button

    Private Sub MainForm_Load(ByVal sender As Object, ByVal e As EventArgs) _
        Handles Me.Load

        InitializeData()
    End Sub


    Private Sub InitializeData()
        bindingSource1 = New System.Windows.Forms.BindingSource()
        Dim dataset1 As New DataSet()
        ClientSize = New System.Drawing.Size(292, 266)

        ' Some xml data to populate the DataSet with.
        ' Some xml data to populate the DataSet with.
        Dim musicXml As String = "<?xml version='1.0' encoding='UTF-8'?>" & _
            "<music><recording><artist>Dave Matthews</artist>" & _
            "<cd>Under the Table and Dreaming</cd>" & _
            "<releaseDate>1994</releaseDate><rating>3.5</rating></recording>" & _
            "<recording><artist>Coldplay</artist><cd>X&amp;Y</cd>" & _
            "<releaseDate>2005</releaseDate><rating>4</rating></recording>" & _
            "<recording><artist>Dave Matthews</artist>" & _
            "<cd>Live at Red Rocks</cd>" & _
            "<releaseDate>1997</releaseDate><rating>4</rating></recording>" & _
            "<recording><artist>U2</artist>" & _
            "<cd>Joshua Tree</cd><releaseDate>1987</releaseDate>" & _
            "<rating>5</rating></recording>" & _
            "<recording><artist>U2</artist>" & _
            "<cd>How to Dismantle an Atomic Bomb</cd>" & _
            "<releaseDate>2004</releaseDate><rating>4.5</rating></recording>" & _
            "<recording><artist>Natalie Merchant</artist>" & _
            "<cd>Tigerlily</cd><releaseDate>1995</releaseDate>" & _
            "<rating>3.5</rating></recording>" & _
            "</music>"

        ' Read the xml.
        Dim reader As New System.IO.StringReader(musicXml)
        dataset1.ReadXml(reader)

        ' Get a DataView of the table contained in the dataset.
        Dim tables As DataTableCollection = dataset1.Tables
        Dim view1 As New DataView(tables(0))

        ' Create a DataGridView control and add it to the form.
        Dim datagridview1 As New DataGridView()
        datagridview1.ReadOnly = True
        datagridview1.AutoGenerateColumns = True
        datagridview1.Width = 300
        Me.Controls.Add(datagridview1)
        bindingSource1.DataSource = view1
        datagridview1.DataSource = bindingSource1
        datagridview1.Columns.Remove("artist")
        datagridview1.Columns.Remove("releaseDate")

        ' Create and add a button to the form. 
        button1 = New Button()
        button1.AutoSize = True
        button1.Text = "Show/Edit Details"
        Me.Controls.Add(button1)
        button1.Location = New Point(50, 200)

    End Sub

    ' Handle the BindingComplete event to ensure the two forms
    ' remain synchronized.
    Private Sub bindingSource1_BindingComplete(ByVal sender As Object, _
        ByVal e As BindingCompleteEventArgs) Handles bindingSource1.BindingComplete
        If e.BindingCompleteContext = BindingCompleteContext.DataSourceUpdate _
            AndAlso e.Exception Is Nothing Then
            e.Binding.BindingManagerBase.EndCurrentEdit()
        End If

    End Sub

    ' The detailed form will be shown when the button is clicked.
    Private Sub button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
        Handles button1.Click

        Dim detailForm As New DetailForm(bindingSource1)
        detailForm.Show()
    End Sub


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

    End Sub
End Class

' The detail form class. 
Public Class DetailForm
    Inherits Form
    Private formDataSource As BindingSource

    ' The constructor takes a BindingSource object.
    Public Sub New(ByVal dataSource As BindingSource)
        formDataSource = dataSource
        Me.ClientSize = New Size(240, 200)
        Dim textBox1 As New TextBox()
        Me.Text = "Selection Details"
        textBox1.Width = 220
        Dim textBox2 As New TextBox()
        Dim textBox3 As New TextBox()
        Dim textBox4 As New TextBox()
        textBox4.Width = 30
        textBox3.Width = 50

        ' Associate each text box with a column from the data source.
        textBox1.DataBindings.Add("Text", formDataSource, "cd", _
            True, DataSourceUpdateMode.OnPropertyChanged)

        textBox2.DataBindings.Add("Text", formDataSource, "artist", True)
        textBox3.DataBindings.Add("Text", formDataSource, "releaseDate", True)
        textBox4.DataBindings.Add("Text", formDataSource, "rating", True)
        textBox1.Location = New Point(10, 10)
        textBox2.Location = New Point(10, 40)
        textBox3.Location = New Point(10, 80)
        textBox4.Location = New Point(10, 120)
        Me.Controls.AddRange(New Control() {textBox1, textBox2, textBox3, _
            textBox4})

    End Sub
End Class
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Data;

namespace BindingSourceMultipleForms
{
    public class MainForm : Form
    {
        public MainForm()
        {
            this.Load += new EventHandler(MainForm_Load);
        }

        private BindingSource bindingSource1;
        private Button button1;

        private void MainForm_Load(object sender, EventArgs e)
        {
            InitializeData();
        }

        private void InitializeData()
        {
            bindingSource1 = new System.Windows.Forms.BindingSource();

            // Handle the BindingComplete event to ensure the two forms
            // remain synchronized.
            bindingSource1.BindingComplete +=  
                new BindingCompleteEventHandler(bindingSource1_BindingComplete);
            ClientSize = new System.Drawing.Size(292, 266);
            DataSet dataset1 = new DataSet();

            // Some xml data to populate the DataSet with.
            string musicXml =
                "<?xml version='1.0' encoding='UTF-8'?>" +
                "<music>" +
                 "<recording><artist>Dave Matthews</artist>" +
                 "<cd>Under the Table and Dreaming</cd>" + 
                 "<releaseDate>1994</releaseDate><rating>3.5</rating></recording>" +
                 "<recording><artist>Coldplay</artist><cd>X&amp;Y</cd>" + 
                 "<releaseDate>2005</releaseDate><rating>4</rating></recording>" +
                 "<recording><artist>Dave Matthews</artist>" + 
                 "<cd>Live at Red Rocks</cd>" + 
                 "<releaseDate>1997</releaseDate><rating>4</rating></recording>" +
                 "<recording><artist>U2</artist>" + 
                 "<cd>Joshua Tree</cd><releaseDate>1987</releaseDate>" + 
                 "<rating>5</rating></recording>" +
                 "<recording><artist>U2</artist>" +
                 "<cd>How to Dismantle an Atomic Bomb</cd>" + 
                 "<releaseDate>2004</releaseDate><rating>4.5</rating></recording>" +
                 "<recording><artist>Natalie Merchant</artist>" +
                 "<cd>Tigerlily</cd><releaseDate>1995</releaseDate>" +
                 "<rating>3.5</rating></recording>" +
                 "</music>";

            // Read the xml.
            System.IO.StringReader reader = new System.IO.StringReader(musicXml);
            dataset1.ReadXml(reader); 

            // Get a DataView of the table contained in the dataset.
            DataTableCollection tables = dataset1.Tables;
            DataView view1 = new DataView(tables[0]);

            // Create a DataGridView control and add it to the form.
            DataGridView datagridview1 = new DataGridView();
            datagridview1.ReadOnly = true;
            datagridview1.AutoGenerateColumns = true;
            datagridview1.Width = 300;
            this.Controls.Add(datagridview1);
            bindingSource1.DataSource = view1;
            datagridview1.DataSource = bindingSource1;
            datagridview1.Columns.Remove("artist");
            datagridview1.Columns.Remove("releaseDate");

            // Create and add a button to the form. 
            button1 = new Button();
            button1.AutoSize = true;
            button1.Text = "Show/Edit Details";
            this.Controls.Add(button1);
            button1.Location = new Point(50, 200);
            button1.Click += new EventHandler(button1_Click);
        }

        // Handle the BindingComplete event to ensure the two forms
        // remain synchronized.
        private void bindingSource1_BindingComplete(object sender, BindingCompleteEventArgs e)
        {
            if (e.BindingCompleteContext == BindingCompleteContext.DataSourceUpdate
                && e.Exception == null)
                e.Binding.BindingManagerBase.EndCurrentEdit();
        }

        // The detailed form will be shown when the button is clicked.
        private void button1_Click(object sender, EventArgs e)
        {
            DetailForm detailForm = new DetailForm(bindingSource1);
            detailForm.Show();
        }

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

    // The detail form class. 
    public class DetailForm : Form
    {
        private BindingSource formDataSource;

        // The constructor takes a BindingSource object.
        public DetailForm(BindingSource dataSource)
        {
            formDataSource = dataSource;
            this.ClientSize = new Size(240, 200);
            TextBox textBox1 = new TextBox();
            this.Text = "Selection Details";
            textBox1.Width = 220;
            TextBox textBox2 = new TextBox();
            TextBox textBox3 = new TextBox();
            TextBox textBox4 = new TextBox();
            textBox4.Width = 30;
            textBox3.Width = 50;

            // Associate each text box with a column from the data source.
            textBox1.DataBindings.Add("Text", formDataSource, "cd", true, DataSourceUpdateMode.OnPropertyChanged);

            textBox2.DataBindings.Add("Text", formDataSource, "artist", true);
            textBox3.DataBindings.Add("Text", formDataSource, "releaseDate", true);
            textBox4.DataBindings.Add("Text", formDataSource, "rating", true);
            textBox1.Location = new Point(10, 10);
            textBox2.Location = new Point(10, 40);
            textBox3.Location = new Point(10, 80);
            textBox4.Location = new Point(10, 120);
            this.Controls.AddRange(new Control[] { textBox1, textBox2, textBox3, textBox4 });
        }

    }
}

編譯程式碼

這個範例需要:

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

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

請參閱

工作

HOW TO:處理資料繫結時所發生的錯誤和例外狀況

其他資源

BindingSource 元件

Windows Form 資料繫結