该行已属于另一张表的解决方法

解决方法有:

一、DataTable.Rows.Add(DataRow.ItemArray);

二、DataTable.ImportRow(DataRow)

三、设置DataTable的tablename,然后.Rows.Add

第一种方法在项目中用到,确实好用!不过感觉第二种应该更好用一些.

若要把A表中的DataRow拷贝到B表中,不能直接B.Row=A.Row;拷贝,要先把A表和B表的结构统一,即A=B.Clone () ;再B.Columns.Add(A.Row.ItemArray)。例1:

                OpenFileDialog file = new OpenFileDialog();
                if (file.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    string path = file.FileName;
                    DTable dbf = new DTable();
                    _tableInvalid = new DataTable();
                    _tableFliter = new DataTable();
                    dbf.Load(path);
                    if (dbf.Table.Rows.Count > 0)
                    {
                        this.GrcInitialData.DataSource = dbf.Table;
                        _tabInitial = new DataTable();
                        _tabInitial = dbf.Table;
                        _tableFliter = _tabInitial.Clone();
                        _tableInvalid = _tabInitial.Clone();
                    }

                    foreach (DataRow item in _tabInitial.Rows)
                    {
                        string bccm = item["N_BCCM"].ToString();//本次抄码
                        string cjsl = item["N_CJSL"].ToString();//抄见水量

                        if (string.IsNullOrEmpty(bccm) || string.IsNullOrEmpty(cjsl) || int.Parse(bccm) < 10 || (int.Parse(bccm) > 10 && int.Parse(cjsl) < 2))
                        {

                            _tableInvalid.Rows.Add(item.ItemArray);//注意
                        }
                        else
                        {
                            _tableFliter.Rows.Add(item.ItemArray);//注意
                        }
                    }
                }

        例2:

       DataTable sourceTable = null;

            sourceTable = GetTest(tableName);

            if (sourceTable == null)

            {return null;}

            DataTable retTable = new DataTable();

            foreach (DataRow dr in sourceTable.Rows)

            { if (dr["主键"].ToString() != "")

                { retTable.Rows.Add(dr.ItemArray);}

            }

原文地址:https://www.cnblogs.com/len0031/p/3956437.html