VB.Net - DataTable

A DataTable object represents a table in a database. But that table has been loaded into memory, and that memory is contained within rows in that DataTable object.

code sample - updating a DataTable with data from a few controls on a table.

1
2
3
4
5
6
7
8
9
10
11
12
13
Dim dt As DataTable = Me.dsWO.Tables("active_wo_Activity_Tasks")  ' Get a table from the dataset

For Each aRow As DataRow In dt.Rows ' Get each row from the table
aRow.Item("Status") = cboTaskStatus.Text ' Place a value into a column
If txtTaskDateCompleted.Text.Length > 0 Then
aRow.Item("DateClosed") = txtTaskDateCompleted.Text
Else
aRow.Item("DateClosed") = DBNull.Value ' Force a null value into the column
End If
aRow.Item("Note") = Mid(txtTaskNote.Text, 1, 500)
aRow.Item("Who_Signed_Off") = cboTaskWho.Text
aRow.Item("Mark") = 0
Next

Code Sample - setting a date field in a data column to null.

It turns out this is fairly tricky

Nulling a date

1
2
3
'Me.dsWO.active_wo(0).DTCompleted = DBNull.Value
'Me.dsWO.active_wo(0).DTCompleted = SqlTypes.SqlDateTime.Null
Me.dsWO.active_wo(0).DTCompleted = System.Convert.DBNull

code sample - drop a column out of a data table.

1
2
dt = acn.GetSchema("Columns", Restrictions)
dt.Columns.Remove("TABLE_CATALOG")

code sample - adding a column to a data table.

1
2
3
dt.Columns.Add( _
"DestinationColumnName", _
System.Type.GetType("System.String"))

With the last 3 samples, you are just changing the in-memory representation of the data table. Not the physical table itself.

More Samples

  • [[CopyDataTable]]
  • [[SortingDatatable]]