演练:将数据绑定到“Word 操作”窗格上的控件
此演练演示如何在 Microsoft Office Word 中将数据绑定到操作窗格上的控件。 这些控件演示 SQL Server 数据库中的表之间的主/从关系。
**适用于:**本主题中的信息适用于 Word 2007 和 Word 2010 的文档级项目。有关更多信息,请参见按 Office 应用程序和项目类型提供的功能。
本演练阐释了以下任务:
使用绑定到数据的 Windows 窗体控件来创建操作窗格。
使用主/从关系在控件中显示数据。
在打开应用程序时显示操作窗格。
提示
以下说明中的某些 Visual Studio 用户界面元素在计算机上出现的名称或位置可能会不同。 您安装的 Visual Studio 版本以及使用的设置决定了这些元素。 有关更多信息,请参见 使用设置。
系统必备
您需要以下组件来完成本演练:
-
Visual Studio 2010 的一个版本,其中包含 Microsoft Office 开发工具。有关更多信息,请参见[将计算机配置为开发 Office 解决方案](bb398242\(v=vs.100\).md)。
Word 2007 或 Word 2010。
访问带有 Northwind SQL Server 示例数据库的服务器。
从 SQL Server 数据库中读取数据和向其中写入数据的权限。
创建项目
第一步是创建 Word 文档项目。
创建新项目
创建一个名为“我的 Word 操作窗格”的 Word 文档项目。 在向导中,选择**“创建新文档”**。
有关更多信息,请参见 如何:在 Visual Studio 中创建 Office 项目。
Visual Studio 会在设计器中打开新的 Word 文档,并将**“我的 Word 操作窗格”项目添加到“解决方案资源管理器”**中。
向操作窗格中添加控件
在此演练中,需要一个包含数据绑定 Windows 窗体控件的操作窗格控件。 向项目中添加一个数据源,然后将控件从**“数据源”**窗口拖动到操作窗格控件中。
添加操作窗格控件
在**“解决方案资源管理器”中选择“我的 Word 操作窗格”**项目。
在**“项目”菜单上,单击“添加新项”**。
在**“添加新项”对话框中选择“操作窗格控件”,将它命名为“ActionsControl”,然后单击“添加”**。
向项目中添加新的数据源
如果**“数据源”窗口不可见,请单击“数据”菜单上的“显示数据源”**。
提示
如果“显示数据源”不可用,请单击 Word 文档,然后再次进行检查。
单击**“添加新数据源”以启动“数据源配置向导”**。
选择**“数据库”,然后单击“下一步”**。
选择到 Northwind 示例 SQL Server 数据库的数据连接,或者使用**“新建连接”**按钮添加新连接。
单击**“下一步”**。
如果选择了该选项,请将其清除以保存连接,然后单击**“下一步”**。
展开**“数据库对象”窗口中的“表”**节点。
选择**“Suppliers”表和“Products”**表旁边的复选框。
单击**“完成”**。
向导将**“Suppliers”表和“Products”表添加到“数据源”窗口中。 还将一个类型化数据集添加到在“解决方案资源管理器”**中可见的项目中。
将数据绑定 Windows 窗体控件添加到操作窗格控件
在**“数据源”窗口中展开“Suppliers”**表。
单击**“Company Name”节点上的下拉箭头并选择“ComboBox”**。
将**“CompanyName”从“数据源”**窗口拖动到操作窗格控件中。
操作窗格控件中便会创建一个 ComboBox 控件。 同时,会将一个名为 SuppliersBindingSource 的 BindingSource、一个表适配器和一个 DataSet 添加到组件栏的项目中。
选择**“组件”**栏中的 SuppliersBindingNavigator 并按 Delete。 在此演练中您将不会使用 SuppliersBindingNavigator。
提示
删除 SuppliersBindingNavigator 并不会移除为其生成的所有代码。 您可以移除此代码。
移动组合框,使其位于标签之下,并将**“Size”**属性更改为“171, 21”。
在**“数据源”窗口中,展开“Suppliers”表的子表“Products”**。
单击**“ProductName”节点上的下拉箭头,然后选择“ListBox”**。
将**“ProductName”**拖动到操作窗格控件中。
操作窗格控件中便会创建一个 ListBox 控件。 同时,会将一个名为 ProductBindingSource 的 BindingSource 和一个表适配器添加到组件栏的项目中。
移动列表框,使其位于标签之下,并将**“Size”**属性更改为“171,95”。
将 Button 从**“工具箱”**拖动到操作窗格控件上,并将其置于列表框下面。
右击 Button,单击快捷菜单上的**“属性”**并更改以下属性。
Property
值
Name
Insert
Text
Insert
调整用户控件的大小,使其适合这些控件。
设置数据源
若要设置数据源,请将代码添加到操作窗格控件的 Load 事件以使用 DataTable 中的数据填充控件,并为每个控件设置 DataSource 和 DataMember 属性。
使用数据加载控件
在 ActionsControl 类的 Load 事件处理程序中,添加以下代码。
Private Sub ActionsControl_Load(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles Me.Load Me.SuppliersTableAdapter.Fill(Me.NorthwindDataSet.Suppliers) Me.ProductsTableAdapter.Fill(Me.NorthwindDataSet.Products) End Sub
private void ActionsControl_Load(object sender, EventArgs e) { this.suppliersTableAdapter.Fill(this.northwindDataSet.Suppliers); this.productsTableAdapter.Fill(this.northwindDataSet.Products); }
在 C# 中,必须将事件处理程序附加到 Load 事件。 可以将这些代码放在 ActionsControl 构造函数中 InitializeComponent 调用的后面。 有关如何创建事件处理程序的更多信息,请参见如何:在 Office 项目中创建事件处理程序。
this.Load += new EventHandler(ActionsControl_Load);
设置控件的数据绑定属性
选择 CompanyNameComboBox 控件。
在**“属性”窗口中单击“DataSource”属性右侧的按钮,然后选择“SuppliersBindingSource”**。
单击**“DisplayMember”属性右侧的按钮,然后选择“CompanyName”**。
展开**“DataBindings”属性,单击“Text”属性右侧的按钮,然后选择“None”**。
选择 ProductNameListBox 控件。
在**“属性”窗口中单击“DataSource”属性右侧的按钮,然后选择“productsBindingSource”**。
单击**“DisplayMember”属性右侧的按钮,然后选择“ProductName”**。
展开**“DataBindings”属性,单击“SelectedValue”属性右侧的按钮,然后选择“None”**。
添加方法以将数据插入表中
下一个任务是从绑定控件中读取数据并填充 Word 文档中的表。 首先,创建一个用于设置表格标题格式的过程,然后添加 AddData 方法以创建一个 Word 表并设置其格式。
设置表格标题的格式
在 ActionsControl 类中创建一个方法,用以设置表格标题的格式。
Shared Sub SetHeadings(ByVal tblCell As Word.Cell, ByVal text As String) With tblCell.Range .Text = text .Font.Bold = True .ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter End With End Sub
static void SetHeadings(Microsoft.Office.Interop.Word.Cell tblCell, string text) { tblCell.Range.Text = text; tblCell.Range.Font.Bold = 1; tblCell.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphCenter; }
创建表
在 ActionsControl 类中编写一个方法,此方法将在不存在表的情况下创建一个表,并将操作窗格中的数据添加到此表中。
Private Sub AddData(ByVal row As System.Data.DataRow, ByVal companyName As String) ' Create a table if it doesn't already exist. If Globals.ThisDocument.Tables.Count = 0 Then Try ' Create a table. Dim tbl As Word.Table = Globals.ThisDocument.Tables.Add( _ Globals.ThisDocument.Application.Selection.Range, 1, 4) ' Insert headings. SetHeadings(tbl.Cell(1, 1), "Company Name") SetHeadings(tbl.Cell(1, 2), "Product Name") SetHeadings(tbl.Cell(1, 3), "Quantity") SetHeadings(tbl.Cell(1, 4), "Unit Price") Catch ex As Exception MessageBox.Show("Problem creating Products table: " & ex.Message, _ "Actions Pane", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try End If ' Add data from data row to the table. Dim selection As Word.Selection = Globals.ThisDocument.Application.Selection If selection.Tables.Count > 0 Then Dim newRow As Word.Row = Globals.ThisDocument.Tables(1).Rows.Add() With newRow .Range.Font.Bold = False .Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphLeft .Cells(4).Range.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight .Cells(1).Range.Text = companyName .Cells(2).Range.Text = row.Item("ProductName").ToString .Cells(3).Range.Text = row.Item("QuantityPerUnit").ToString .Cells(4).Range.Text = Math.Round(row.Item("UnitPrice"), 2) End With Else MessageBox.Show("Cursor must be within a table.", _ "Actions Pane", MessageBoxButtons.OK, MessageBoxIcon.Error) End If End Sub
private void AddData(System.Data.DataRow row, string companyName) { object missing = System.Type.Missing; // Create a table if it doesn't already exist. if (Globals.ThisDocument.Tables.Count == 0) { try { // Create a table. Microsoft.Office.Interop.Word.Table tbl = Globals.ThisDocument.Tables.Add (Globals.ThisDocument.Application.Selection.Range, 1, 4, ref missing, ref missing); // Insert headings. SetHeadings(tbl.Cell(1, 1), "Company Name"); SetHeadings(tbl.Cell(1, 2), "Product Name"); SetHeadings(tbl.Cell(1, 3), "Quantity"); SetHeadings(tbl.Cell(1, 4), "Unit Price"); } catch (Exception ex) { MessageBox.Show("Problem creating Products table: " + ex.Message, "Actions Pane", MessageBoxButtons.OK, MessageBoxIcon.Error); } } // Add data from data row to the table. Microsoft.Office.Interop.Word.Selection selection = Globals.ThisDocument.Application.Selection; if (selection.Tables.Count > 0) { Microsoft.Office.Interop.Word.Row newRow = Globals.ThisDocument.Tables[1].Rows.Add(ref missing); newRow.Range.Font.Bold = 0; newRow.Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphLeft; newRow.Cells[4].Range.ParagraphFormat.Alignment = Microsoft.Office.Interop.Word.WdParagraphAlignment.wdAlignParagraphRight; newRow.Cells[1].Range.Text = companyName; newRow.Cells[2].Range.Text = row["ProductName"].ToString(); newRow.Cells[3].Range.Text = row["QuantityPerUnit"].ToString(); newRow.Cells[4].Range.Text = Math.Round(Convert.ToDouble(row["UnitPrice"])).ToString("#,##0.00"); } else { MessageBox.Show("Cursor must be within a table.", "Actions Pane", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
在 Word 表中插入文本
将以下代码添加到**“插入”**按钮的 Click 事件处理程序中。
Private Sub Insert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Insert.Click Dim tbl As System.Data.DataTable = NorthwindDataSet.Products Dim rows() As System.Data.DataRow ' Check if a product is selected. If Not Me.ProductNameListBox.SelectedIndex < 0 Then Dim product As String = Me.ProductNameListBox.SelectedItem.Row.Item("ProductName") Dim company As String = Me.CompanyNameComboBox.Text ' Return the data row from the selected Product in the list box. rows = tbl.Select("[ProductName] = '" & product.Replace("'", "''") & "'") AddData(rows(0), company) Else MessageBox.Show("Please select a product.", "Actions Pane", MessageBoxButtons.OK) End If End Sub
private void Insert_Click(object sender, System.EventArgs e) { System.Data.DataTable tbl = northwindDataSet.Products; System.Data.DataRow[] rows; // Check if a product is selected. if (this.productNameListBox.SelectedIndex >= 0) { System.Data.DataRowView productRow = (System.Data.DataRowView)this.productNameListBox.SelectedItem; string product = productRow.Row["ProductName"].ToString(); string company = this.companyNameComboBox.Text; // Return the data row from the selected product. rows = tbl.Select("[ProductName] = '" + product.Replace("'", "''") + "'"); this.AddData(rows[0], company); } else { MessageBox.Show("Please select a product.", "Actions Pane", MessageBoxButtons.OK); } }
在 C# 中,必须为按钮的 Click 事件创建事件处理程序。 可以将此代码放置在 ActionsControl 类的 Load 事件处理程序中。
this.Insert.Click += new EventHandler(Insert_Click);
显示操作窗格
将控件添加到操作窗格之后,操作窗格即变为可见。
显示操作窗格
在**“解决方案资源管理器”中右击“ThisDocument.vb”或“ThisDocument.cs”,再单击快捷菜单上的“查看代码”**。
在 ThisDocument 类的顶部创建一个新的控件实例,使其看上去与下面的示例类似。
Dim actions As New ActionsControl
private ActionsControl actions = new ActionsControl();
向 ThisDocument 的 Startup 事件处理程序中添加代码,使其看上去与下面的示例类似。
Me.ActionsPane.Controls.Add(actions)
this.ActionsPane.Controls.Add(actions);
测试应用程序
现在可以对文档进行测试,以验证当文档打开时是否出现操作窗格。 测试操作窗格上控件之间的主/从关系,并确保单击**“插入”**按钮时数据会填充到 Word 表中。
测试文档
按 F5 运行项目。
确认操作窗格可见。
从组合框中选择一个公司,并确认**“Products”**列表框中的项随之发生变化。
选择一个产品,单击操作窗格上的**“插入”**,并确认产品详细信息会随之添加到 Word 表中。
插入来自不同公司的其他产品。
后续步骤
此演练演示将数据绑定到 Word 操作窗格中的控件的基本操作。 下一步可能要执行以下几项任务:
将数据绑定到 Excel 中的控件。 有关更多信息,请参见演练:将数据绑定到 Excel 操作窗格上的控件。
显示和隐藏操作窗格上的控件。 有关更多信息,请参见演练:根据用户上下文更改操作窗格。
部署项目。 有关更多信息,请参见部署概述(Visual Studio 中的 Office 开发)。