using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace chxboxs { public partial class Form1 : Form { private DataTable table1; private void Form1_Load(object sender, EventArgs e) { 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 <=2; i++) { row = table1.NewRow(); row["id"] = i; row["item"] = i; table1.Rows.Add(row); } // Accept changes. table1.AcceptChanges(); //PrintValues(table1, "Original values"); this.dataGridView2.DataSource = table1; // Create a second DataTable identical to the first. } private void button2_Click(object sender, EventArgs e) { DataTable table2 = table1.Clone(); DataRow row; 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); table1.Merge(table2); this.dataGridView2.DataSource = table1; } private Form2 f2; public Form1() { InitializeComponent(); } private void Form1_KeyDown(object sender, KeyEventArgs e) { this.label1.Text = e.KeyCode.ToString(); } private void button1_Click(object sender, EventArgs e) { if (f2 == null||f2.IsDisposed) { f2 = new Form2(); f2.Show(); } else { f2.Activate(); } } } } 将指定的 DataTable 与当前的 DataTable 合并。