DataTable間でDataRowをコピーする [.NET]
失敗例
最初、何も考えずにこうかなと考えて作ったら失敗しました。1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | Private Sub CopyDataRow() 'データテーブルAの作成' Dim oTblA As DataTable = New DataTable oTblA.Columns.Add( "shain_cd" ) oTblA.Columns.Add( "shain_nm" ) oTblA.Columns.Add( "remarks" ) '5行作成' For nRow As Integer = 0 To 4 Dim oRow As DataRow = oTblA.NewRow oRow( "shain_cd" ) = 1 oRow( "shain_nm" ) = "社員" & nRow oRow( "remarks" ) = nRow oTblA.Rows.Add(oRow) Next 'データテーブルAからデータテーブルBを作成' Dim oTblB As DataTable = oTblA.Clone 'データテーブルAの先頭行を取得し、データテーブルBに追加' Dim oRowCopy As DataRow = oTblA.Rows(0) oTblB.Rows.Add(oRowCopy) End Sub |
oRowCopyはoTblAに属しているから移動できないとのことでした。
ImportRow
この場合はImportRowを使用します。1 2 | oTblB.ImportRow(oRowCopy) |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | Private Sub CopyDataRow() 'データテーブルAの作成' Dim oTblA As DataTable = New DataTable oTblA.Columns.Add( "shain_cd" ) oTblA.Columns.Add( "shain_nm" ) oTblA.Columns.Add( "remarks" ) '5行作成' For nRow As Integer = 0 To 4 Dim oRow As DataRow = oTblA.NewRow oRow( "shain_cd" ) = 1 oRow( "shain_nm" ) = "社員" & nRow oRow( "remarks" ) = nRow oTblA.Rows.Add(oRow) Next 'データテーブルAからデータテーブルBを作成' Dim oTblB As DataTable = oTblA.Clone 'データテーブルAの先頭行を取得し、データテーブルBに追加' Dim oRowCopy As DataRow = oTblA.Rows(0) oTblB.ImportRow(oRowCopy) End Sub |
結果(イミディエイトウインドウ)
1 2 3 4 5 6 | ? otblB.Rows(0)("shain_cd") "1" {String} String: "1" ? otblB.Rows(0)("shain_nm") "社員0" {String} String: "社員0" |
コメント
コメントを投稿