如何:使用 BindingSource 组件跨窗体共享绑定数据

使用 BindingSource 组件,可以轻松地跨窗体共享数据。 例如,您可能希望显示一个汇总数据源数据的只读窗体,以及另一个包含数据源中当前所选项相关详细信息的可编辑窗体。 此示例演示这种方案。

示例

下面的代码示例演示如何跨窗体共享 BindingSource 及其绑定数据。 在此示例中,共享的 BindingSource 被传递到子窗体的构造函数。 子窗体允许用户编辑主窗体中当前所选项的数据。

提示

在该示例中对 BindingSource 组件的 BindingComplete 事件进行处理,以确保两个窗体保持同步。 有关执行此操作的原因的更多信息,请参见如何:确保绑定到同一数据源的多个控件保持同步

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 中生成此示例。 有关更多信息,请参见 如何:使用 Visual Studio 编译和运行完整的 Windows 窗体代码示例如何:使用 Visual Studio 编译和运行完整的 Windows 窗体代码示例如何:使用 Visual Studio 编译和运行完整的 Windows 窗体代码示例如何:使用 Visual Studio 编译和运行完整的 Windows 窗体代码示例如何:使用 Visual Studio 编译和运行完整的 Windows 窗体代码示例.

请参见

任务

如何:处理因数据绑定而发生的错误和异常

其他资源

BindingSource 组件

Windows 窗体数据绑定