将DataTable的内容传播到3个DataGridViews中

时间:2010-08-09 08:48:23

标签: c# .net winforms datagridview

假设我有一个运行存储过程的表单。 此存储过程在表中创建一些具有预生成值的行,并返回一个包含此存储过程创建的行的DataTable。

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

我有点困惑如何将单个DataTable中的信息显示到三个不同的DataGridViews中,并且仍然可以通过用户对DataGridViews所做的更改来轻松更新数据库。

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

是否有更好的方法来实现这一目标,而不是首先拆分主DataTable?

提前多多感谢。

2 个答案:

答案 0 :(得分:2)

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

当你声明:

 dataGridView1.DataSource = dataTable1;

您实际上正在使用表的默认DataView。您正在寻找类似的东西:

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

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

答案 1 :(得分: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;
    }