DataTable拷贝DataRow

一开始,思路是这样的:

DataTable dt = SqlHelper.GetTable("select * from Person");
DataTable dt2 = dt.Clone();
DataRow dr = dt.Rows[0];
dt2.Rows.Add(dr);
Console.ReadKey();

遗憾的是,将会抛出一个异常:

 

 

修改后的实现方式:

DataTable dt = SqlHelper.GetTable("select * from Person");
DataTable dt2 = dt.Clone();
DataRow dr = dt.Rows[0];
dt2.Rows.Add(dr.ItemArray);
Console.ReadKey();

或者 :

DataTable dt = SqlHelper.GetTable("select * from Person");
DataTable dt2 = dt.Clone();
DataRow dr = dt.Rows[0];
dt2.ImportRow(dr);
Console.ReadKey();

 

最后附上SqlHelper:

static class SqlHelper
{
    private static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;

    public static DataTable GetTable(string sql, params SqlParameter[] paras)
    {
        using (SqlConnection conn = new SqlConnection(ConnectionString))
        {
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.AddRange(paras);
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            conn.Open();
            adapter.Fill(ds);
            return ds.Tables[0];
        }
    }
}
View Code

 

posted @ 2018-02-04 11:49  Jichan·Jong  阅读(650)  评论(0编辑  收藏  举报