| 发表于:2007-02-09 11:07:592楼 得分:20 |
示例如下: 下面的控制台应用程序创建一个简单的 datatable 并将数据添加到该表中。该示例随后创建该表的一个副本,并向该副本添加行。最后,该示例调用 merge 方法将第二个表中的数据与第一个表中的数据合并。 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 rowchanged event handler for the table. table1.rowchanged += new system.data.datarowchangeeventhandler(row_changed); // 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 "); } private static void row_changed(object sender, datarowchangeeventargs e) { console.writeline( "row changed {0}\t{1} ", e.action, e.row.itemarray[0]); } private static void printvalues(datatable table, string label) { // display the values in the supplied datatable: console.writeline(label); foreach (datarow row in table.rows) { foreach (datacolumn col in table.columns) { console.write( "\t " + row[col].tostring()); } console.writeline(); } } | | |
|