C#中将原表复制到新表
源程序来自网络上的资源,我记录下来用于以后忘记之用。对大家也许有用
//表dataTableSource获取数据
string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info = False;" +
"Data Source = D:\\vb60\\mdb\\NorthWind.mdb";
OleDbConnection Conn = new OleDbConnection(ConnectionString);
Conn.Open();
OleDbDataAdapter Ada = new OleDbDataAdapter("Select * From Orders",Conn);
DataTable dataTableSource = new DataTable();
Ada.Fill(dataTableSource);
dataGrid1.DataSource = dataTableSource;
//创建新表dataTableDest
DataTable dataTableDest = new DataTable();
//将表dataTableSource的结构复制到新表dataTableDest中
dataTableDest = dataTableSource.Clone();
//然后再复制数据到新表中
foreach(DataRow dr in dataTableSource.Rows)
{
//使用ImportRow()方法复制数据。若用dataTableDest.Rows.Add(dr)将会出错:System.ArgumentException: 该行已经属于另一个表。
dataTableDest.ImportRow(dr);
}
dataGrid2.DataSource = dataTableDest;
Conn.Close();
//表dataTableSource获取数据
string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info = False;" +
"Data Source = D:\\vb60\\mdb\\NorthWind.mdb";
OleDbConnection Conn = new OleDbConnection(ConnectionString);
Conn.Open();
OleDbDataAdapter Ada = new OleDbDataAdapter("Select * From Orders",Conn);
DataTable dataTableSource = new DataTable();
Ada.Fill(dataTableSource);
dataGrid1.DataSource = dataTableSource;
//创建新表dataTableDest
DataTable dataTableDest = new DataTable();
//将表dataTableSource的结构复制到新表dataTableDest中
dataTableDest = dataTableSource.Clone();
//然后再复制数据到新表中
foreach(DataRow dr in dataTableSource.Rows)
{
//使用ImportRow()方法复制数据。若用dataTableDest.Rows.Add(dr)将会出错:System.ArgumentException: 该行已经属于另一个表。
dataTableDest.ImportRow(dr);
}
dataGrid2.DataSource = dataTableDest;
Conn.Close();