Analysis of the difference between DataTable class Clone method and Copy method

  • 2020-05-27 04:41:31
  • OfStack

The DataTable.Clone method: clones the structure of DataTable, including all the DataTable schemas and constraints.

The DataTable.Copy method: copies the structure and data of the DataTable.

We can write the following program to verify:


        static string connStr = "Server=.\\sqlexpress;Initial Catalog=hr;Integrated Security=True";
        static void Clone()
        {
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                string sql = "select * from emp";
                SqlDataAdapter da = new SqlDataAdapter(sql, conn);
                DataTable dt = new DataTable();
                da.Fill(dt);
                DataTable dtClone = dt.Clone();
                Print(dtClone);
            }
        }
        private static void Print(DataTable dtClone)
        {
            foreach (DataColumn col in dtClone.Columns)
            {
                Console.Write(col.DataType+"\t");
            }
            Console.WriteLine();
            foreach (DataRow row in dtClone.Rows)
            {
                Console.Write(row[0] + "\t" + row[1] + "\t" + row[2] + "\n");
            }
            Console.WriteLine();
        }
        static void Main(string[] args)
        {
            Clone();// Just copy the table structure 
            Copy();// Copy the table structure and data 
            Console.ReadKey();
        }
        private static void Copy()
        {
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                string sql = "select * from emp";
                SqlDataAdapter da = new SqlDataAdapter(sql, conn);
                DataTable dt = new DataTable();
                da.Fill(dt);
                DataTable dtCopy = dt.Copy();
                Print(dtCopy);
            }
        }
    }


Related articles: