如何在保留两个表的同时将两个DataTable绑定到一个DataGridView [英] How do I bind two DataTables to one DataGridView while preserving the two tables

查看:104
本文介绍了如何在保留两个表的同时将两个DataTable绑定到一个DataGridView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将两个DataTable组合在一起并将其绑定到单个DataGridView,这样我仍然可以单独使用两个DataTables,我可以添加,更新或删除行中的任何一个。行更改将反映在表和绑定DataGridView上。我该怎么做?

I want to combine two DataTables together and bind it to a single DataGridView such that I can still use the two DataTables separately in ways that I can add, update, or remove rows to either of them. The row changes will be reflected both on tables and on the bind DataGridView as well. How would I do that?

推荐答案

你好,



你可以使用合并表方法



检查一下,



Hi,

You can use Merge table Method

Check This,

private static void DemonstrateMergeTable()
{
    DataTable table1 = new DataTable("Items");

    // Add columns
    DataColumn column1 = new DataColumn("id", typeof(System.Int32));
    DataColumn column2 = new DataColumn("item", typeof(System.Int32));
    table1.Columns.Add(column1);
    table1.Columns.Add(column2);

    // Set the primary key column.
    table1.PrimaryKey = new DataColumn[] { column1 };

  

    // Add some rows.
    DataRow row;
    for (int i = 0; i <= 3; i++)
    {
        row = table1.NewRow();
        row["id"] = i;
        row["item"] = i;
        table1.Rows.Add(row);
    }

    // Accept changes.
    table1.AcceptChanges();
    PrintValues(table1, "Original values");

    // Create a second DataTable identical to the first.
    DataTable table2 = table1.Clone();

    // Add three rows. Note that the id column can't be the  
    // same as existing rows in the original table.
    row = table2.NewRow();
    row["id"] = 14;
    row["item"] = 774;
    table2.Rows.Add(row);

    row = table2.NewRow();
    row["id"] = 12;
    row["item"] = 555;
    table2.Rows.Add(row);

    row = table2.NewRow();
    row["id"] = 13;
    row["item"] = 665;
    table2.Rows.Add(row);

    // Merge table2 into the table1.
    Console.WriteLine("Merging");
    table1.Merge(table2);
    PrintValues(table1, "Merged With table1");

}







谢谢



Siva Rm K




Thanks

Siva Rm K


在网上搜索解决方案之后,我想这个问题没有简单的解决办法。 DataGridView仅用于处理一个数据源。因此,不可能将两个DataTable组合成一个并将其绑定到DataGridView,而无需克隆或更改这两个表。



因此,唯一的解决方案是是创建另一个包含两个表的内容的表,并在对两个原始表中的任何一个进行更改时更新该表。
After searching around online for a solution, I guess there is no easy solution to this problem. DataGridView is designed for handling only one data source. Thus, it isn't possible to combine two DataTable into one and bind that to DataGridView without having to clone or alter the two tables.

Thus, the only solution would be to create another table with the contents of both tables and update that table whenever changes are made to either of the two originating tables.


这篇关于如何在保留两个表的同时将两个DataTable绑定到一个DataGridView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆