Sunday, June 28, 2009

Copy selective columns of data table to another datatable - VB.NET

The Copy Method of DataTable is used to Copy the whole table to another data table.

But

How to copy selective columns of data table to another data table?


The following VB.NET Code snippet is used to Copy some columns of data table to another table.

It copies

1.EmpId

2.FirstName

3.DateOfJoin

Columns into a new data table.



Private Function CopyColumnsToDataTable(ByVal SourceTable As DataTable) As DataTable

Dim DestTable As DataTable = new DataTable()

'Copy Only three columns from the datatable

Dim strColsToExport() As String={"EmpID","FirstName","DateOfJoin"}


DestTable = sourceTable.DefaultView.ToTable("tempTableName", false, strColsToExport)


Return DestTable

End Function



The following code populates a data table EmpTable with 5 Columns

1. EmpID

2. First Name

3. Last Name

4. Address

5. date of join




Private Sub PopulateDataTable()

Dim sourceDt As DataTable = New DataTable("EmpTable")
Dim DestDt As DataTable

Dim Col1 As DataColumn = sourceDt.Columns.Add("EmpID", Type.GetType("System.Int32"))

col1.AllowDBNull = false
col1.Unique = true

sourceDt.Columns.Add("FirstName", Type.GetType("System.String"))
sourceDt.Columns.Add("LastName", Type.GetType("System.String"))
sourceDt.Columns.Add("Address", Type.GetType("System.String"))
sourceDt.Columns.Add("DateOfJoin", Type.GetType("System.DateTime"))


'Add Some rows to data table

Dim dataRow As DataRow

dataRow = sourceDt.NewRow()

dataRow (0) = 10001
dataRow (1) = "Alan"
dataRow (2) = "Broad"
dataRow (3) = Convert.ToDate ("12\10\2001")

sourceDt.Rows.Add( dataRow)


dataRow = sourceDt.NewRow()

dataRow (0) = 10002
dataRow (1) = "Bob"
dataRow (2) = "Evan"
dataRow (3) = Convert.ToDate ("01\02\2003")

sourceDt.Rows.Add( dataRow)


sourceDt.AcceptChanges()


'Populate EmpID, FirstName and DateOfJoining Columns into a new data table

DestDt = CopyColumnsToDataTable (sourceDt)

'Binding it to a datagridview

Me.DataGridView1.DataSource = DestDt



End Sub

No comments:

Post a Comment