Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
<pre>vb.net I want To copy DataTable To anther DataTable with other columns


What I have tried:

datatable.copy
datatable.clone
Posted
Updated 21-Jul-21 4:40am

You can't do it quite like that: make a copy of your DataTable, and then use the Columns.Add method to extend the copy: Add new column and data to datatable that already contains data - c# - Stack Overflow[^] - the code is C# but it's pretty obvious and there are online converters if you really can't work it out.
 
Share this answer
 
Even if you didn't show us your code, seems you've been pretty close, because you have to use both methods: Clone[^] and Copy[^]. See:

VB.NET
'create sample datatable (source)
Dim dtOrig AS DataTable = New DataTable()
dtOrig.Columns.Add(New DataColumn("Id", Type.GetType("System.Int32")))
dtOrig.Columns.Add(New DataColumn("UserName", Type.GetType("System.String")))
dtOrig.Columns.Add(New DataColumn("IsActive", Type.GetType("System.Boolean")))
dtOrig.Rows.Add(New Object(){1, "Adam", False})
dtOrig.Rows.Add(New Object(){2, "Ariel", True})
dtOrig.Rows.Add(New Object(){3, "Beast", False})
dtOrig.Rows.Add(New Object(){4, "Beauty", True})

''copy columns form original DataTable
Dim dtCopy  AS DataTable = New DataTable()
'create copy of original datatable (structure)
dtCopy = dtOrig.Clone()
'copy data
dtCopy = dtOrig.Copy()
'add new column
dtCopy.Columns.Add(New DataColumn("Salary", Type.GetType("System.Double")))
'insert default value for new column 
For i As Integer = 0 To dtCopy.Rows.Count-1
	Dim dr As DataRow = dtCopy.Rows(i)
	dr("Salary")= 100*(i+1.5)
Next


That's all!
 
Share this answer
 
v2
Use this without Loop

Dim ds as New DataSet

ds.tables.add(dt.Copy)
 
Share this answer
 
Comments
CHill60 21-Jul-21 13:14pm    
What about the additional columns?
Member 4339228 9-Mar-22 9:04am    
add them them datatable.clomns.add

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900