在C#中,BindingNavigator控件通常用于简化对数据源(如DataTable或DataSet)的操作。要使用BindingNavigator绑定多个数据源,你需要为每个数据源创建一个BindingSource对象,并将这些对象添加到BindingNavigator的Bindings集合中。以下是一个简单的示例,展示了如何将两个数据源绑定到BindingNavigator:
Customers和Orders。DataTable customersTable = new DataTable();
customersTable.Columns.Add("CustomerID", typeof(int));
customersTable.Columns.Add("CustomerName", typeof(string));
customersTable.Rows.Add(1, "John Doe");
customersTable.Rows.Add(2, "Jane Smith");
DataTable ordersTable = new DataTable();
ordersTable.Columns.Add("OrderID", typeof(int));
ordersTable.Columns.Add("CustomerID", typeof(int));
ordersTable.Columns.Add("OrderDate", typeof(DateTime));
ordersTable.Rows.Add(1001, 1, DateTime.Now);
ordersTable.Rows.Add(1002, 2, DateTime.Now.AddDays(1));
BindingSource对象,并将它们分别绑定到customersTable和ordersTable。BindingSource customersBindingSource = new BindingSource();
customersBindingSource.DataSource = customersTable;
BindingSource ordersBindingSource = new BindingSource();
ordersBindingSource.DataSource = ordersTable;
BindingSource对象添加到BindingNavigator的Bindings集合中。BindingNavigator bindingNavigator = new BindingNavigator();
bindingNavigator.Bindings.Add(customersBindingSource);
bindingNavigator.Bindings.Add(ordersBindingSource);
BindingNavigator控件添加到窗体上,并为其添加数据绑定。this.Controls.Add(bindingNavigator);
现在,你可以在窗体上使用BindingNavigator来浏览和操作Customers和Orders数据源。请注意,这个示例使用了简单的DataTable作为数据源。在实际应用程序中,你可能需要使用更复杂的数据模型(如实体框架中的类)来表示数据。