2010-08-09 106 views
0

假设我有一个运行存储过程的表单。 此存储过程使用预生成的值在表中创建一些行,并返回包含由此存储过程创建的行的DataTable。将DataTable的内容传播到3 DataGridViews

在窗体上,我需要在3个不同的DataGridView上显示此信息,以便用户可以更改它。 模式是相同的,但每个DataGridViews都会显示不同的类别,因此会在每个DataGridView中隐藏一些不相关的列,但在数据库中它们都是同一个表的一部分。 用户可以在所有3个DataGridView上添加新行。

我有点困惑如何将来自单个DataTable的信息显示为三个不同的DataGridView,并且仍然有一个简单的方法来更新用户对DataGridViews所做更改的数据库。

我假设我可以在其中三个主要DataTable中断,然后将每个DataTable绑定到相关的DataGridView,但是当我想要将更改(更新和新行)保存到数据库考虑到我的更改分散到3个DataTable中而不是单个数据表中?

有没有更好的方法来实现这一点,而不是主要的DataTable分裂?

非常感谢。

回答

2

所有的DataGridView都需要自己的DataView。最简单的方法可能是使用单独的BindingSource组件。

当你说出:

dataGridView1.DataSource = dataTable1; 

您在实际使用表的默认数据视图。你正在寻找类似的东西:

//untested 
var view1 = new DataView(dataTable1); 
dataGridView1.DataSource = view1; 
var view2 = new DataView(dataTable1); 
dataGridView2.DataSource = view2; 

然后你可以使用view1,view2来控制过滤和排序。

+0

谢谢,请你再扩展一下吗? – 2010-08-09 09:09:52

1

非常感谢Henk,您的文章让我走上了正确的轨道,它完美地解决了我的问题。 我现在可以在任何网格视图中添加项目,并且我的DataTable已更新,无需执行像我期望的那样可以完成的任何操作。

为了尝试理解解决方案,我做了一个小测试演示,我想我会在这里发布给未来的读者,因为它包括如何过滤每个DataView以仅包含相关信息。 这是一个示例代码,我没有包括错误检查等。

private DataTable fruitsDataTable = null; 
private DataView orangesDataView = null; 
private DataView applesDataView = null; 

private void Form1_Load(object sender, EventArgs e) 
    { 
     fruitsDataTable = new DataTable("Fruits"); 

     // Dynamically create the DataTable schema for the sake of this example 
     fruitsDataTable.Columns.Add("Category", typeof(string)); 
     fruitsDataTable.Columns.Add("Description", typeof (string)); 
     fruitsDataTable.Columns.Add("Quantity", typeof(int)); 
     fruitsDataTable.Columns.Add("Price", typeof(double)); 

     // Add the fruits to the main table 
     fruitsDataTable.Rows.Add("ORANGE", "Fresh Oranges", 5, 5.50); 

     fruitsDataTable.Rows.Add("APPLE", "Granny Smith Apples", 10, 2.20); 
     fruitsDataTable.Rows.Add("APPLE", "Golden Apples", 40, 1.75); 

     fruitsDataTable.Rows.Add("ORANGE", "Bloody Oranges", 10, 7.99); 

     fruitsDataTable.Rows.Add("BANANA", "Ivory Coast Bananas", 5, 6.99); 

     mainGridView.DataSource = fruitsDataTable; 

     // Create a DataView for each fruit category and bind it to the relevant DataGridView control on the form 
     orangesDataView = new DataView(fruitsDataTable, "Category = 'ORANGE'", string.Empty, DataViewRowState.CurrentRows); 
     orangesGridView.DataSource = orangesDataView; 

     applesDataView = new DataView(fruitsDataTable, "Category = 'APPLE'", string.Empty, DataViewRowState.CurrentRows); 
     applesGridView.DataSource = applesDataView; 
    }