日期:2014-05-18  浏览次数:20490 次

如何复制DataTable过滤部分数据到另一个DataTable
有一个datatable t1 要把 adid列 值为 1,3,5,7 的复制到(DataTable)t2 中

------解决方案--------------------

dt.Select()

查查这方法
------解决方案--------------------
探讨

dt.Select()

查查这方法

------解决方案--------------------
C# code
 System.Data.DataTable dt = new System.Data.DataTable();
            System.Data.DataView dv = new System.Data.DataView(dt);
            dv.RowFilter = "adid in(1,2,3,5,7)";
            System.Data.DataTable dt2 = dv.ToTable();

------解决方案--------------------
C# code
   protected void Page_Load(object sender, EventArgs e)
    {
        DataTable dt1 = new DataTable();
        DataColumn coll = dt1.Columns.Add("id", typeof(Int32));
        DataColumn col2 = dt1.Columns.Add("name", typeof(string));
        DataRow dr = dt1.NewRow();
        dr["id"] = 1;
        dr["name"] = "你好";
        dt1.Rows.Add(dr);

        dr = dt1.NewRow();
        dr["id"] = 2;
        dr["name"] = "你好";
        dt1.Rows.Add(dr);

        dr = dt1.NewRow();
        dr["id"] = 3;
        dr["name"] = "你好";
        dt1.Rows.Add(dr);

        DataTable dt2 = new DataTable();
        DataColumn col3 = dt2.Columns.Add("id", typeof(Int32));
        DataColumn col4 = dt2.Columns.Add("name", typeof(string));
        for (int i = 0; i < dt1.Rows.Count; i++)
        {
            if (dt1.Rows[i]["id"].ToString() == "1" || dt1.Rows[i]["id"].ToString() == "3")
            {
                dt2.ImportRow(dt1.Rows[i]);
            }
        }
        GridView1.DataSource = dt2;
        GridView1.DataBind();
    }