代码之家  ›  专栏  ›  技术社区  ›  Kharlos Dominguez

将DataTable的内容扩展到3个DataGridView中

  •  0
  • Kharlos Dominguez  · 技术社区  · 14 年前

    此存储过程使用预先生成的值在表中创建一些行,并返回一个包含此存储过程创建的行的DataTable。

    在窗体上,我需要在3个不同的datagridview上显示此信息,以便用户可以更改它。 用户可以在所有3个DataGridView上添加新行。

    我有点困惑如何将单个DataTable中的信息显示到三个不同的datagridview中,并且仍然有一种简单的方法可以使用用户对datagridview所做的更改来更新数据库。

    我假设我可以将主数据表拆分为三个数据表,然后将每个数据表绑定到相关的DataGridView,但是当我想将更改(更新的和新行)保存到数据库时,考虑到我的更改被分散到三个数据表而不是一个数据表,这不会带来问题吗?

    2 回复  |  直到 14 年前
        1
  •  2
  •   Henk Holterman    14 年前

    所有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来控制过滤和排序。

        2
  •  1
  •   Kharlos Dominguez    14 年前

    非常感谢亨克,你的帖子让我走上了正轨,完美地解决了我的问题。 我现在可以在任何网格视图上添加项,并且我的数据表也会更新,而不需要像我期望的那样进行任何合并。

    这是一个示例代码,我没有包括错误检查等。

    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;
        }