由於需要對dataTabel中的行進行上移和下移操作:
row 1 行號0
row2 行號1
row3 行號2
例如將row3上移一行,即row2和row3對調位置。
思路:將row3復制出來,刪除row3,在第二行插入row3。
復制row3的方法是: DataRow DR1 = dataTabel.Rows[2];
刪除row3:dataTabel.Rows.RemoveAt(2); //此行將DR1 的內容給刪除了
將DR1插入第二行:DT1.Rows.InsertAt(DR1, 2-1); //插入的是空行
所以上述操作無法完成任務,原因就是DataRow 是引用類型,你刪除目標行時,你意圖復制的行內容也被刪除了。
另想辦法,新建一個dataTabel2,然后把行復制到新表,再將dataTabel2的行插入到dataTabel。
還是不行,插入時,提示行已存在於另一個dataTabel,不能插入。想想也是,如果能插入,dataTabel2不就少了一行,結構不就被破壞了嘛。
復制行的方法:
DataTabel dataTabel2= dataTabel.clone();//必須先復制表的架構,使具有相同的的列或關系!
DataRow DR2 =dataTabel2 . NewRow();
DR2.ItemArray = DR1.ItemArray;
既然不能將其他表的行插入本表,只能想着從本表新建一行,然后插入到相應位置了。於是,問題解決了。一波三折,特記錄之。
//將要上移的行 DataRow DR1 = DT1.Rows[intCurrentRow]; //在當前表中創建一個新行,並把要移動的行的內容復制到新行 DataRow DR2 = DT1.NewRow(); DR2.ItemArray = DR1.ItemArray; //開始移動,刪除要上移的行,再將新行插入到原位置的上一行 DT1.Rows.RemoveAt(intCurrentRow); DT1.Rows.InsertAt(DR2, intCurrentRow-1);
借鑒以下思想:
DataRow復制一行到另一個DataTable
http://www.cnblogs.com/pains/archive/2007/11/22/969003.html
下面兩個方法是DataRow復制一行到另一個DataTable的,直接Add會出錯“此行已屬於另一個表”,其實以前就知道怎么做的,可每次要用到的時候還是犯糊塗,這次把它們記下來。
1.用DataRow.ItemArray
DataTable t=new DataTable();
DataRow r=t.NewRow();
r.ItemArray=oldRow.ItemArray;
t.Rows.Add(r);
2.用DataTable.ImportRow()
t.ImportRow(oldRow);
1.用DataRow.ItemArray
DataTable t=new DataTable();
DataRow r=t.NewRow();
r.ItemArray=oldRow.ItemArray;
t.Rows.Add(r);
2.用DataTable.ImportRow()
t.ImportRow(oldRow);