Visual Basic World

Just another Visual Basic weblog

Visual Studio 2005 Cookbook – Database, Creating In-Memory Data Tables Manually

Recipe 13.8. Creating In-Memory Data Tables Manually

Problem

You want to manage some data in a database-table-like fashion, but the source data is not coming from a database, or from anything that looks like a table.

Solution

Build a DataTable manually, and fill in all the table details and data yourself.

Discussion

The following code builds a simple table of state information and adds two records:

	Dim stateTable As DataTable = New DataTable("UnitedStates")

	' ----- Use the abbreviation as the primary key.
	Dim priKeyCol(0) As Data.DataColumn
	priKeyCol(0) = stateTable.Columns.Add("ShortName", GetType(String))
	stateTable.PrimaryKey = priKeyCol

	' ----- Add other data columns.
	stateTable.Columns.Add("FullName", GetType(String))
	stateTable.Columns.Add("Admission", GetType(Date))
	stateTable.Columns.Add("Population", GetType(Long))

	' ----- Add a record.
	Dim stateInfo As Data.DataRow = stateTable.NewRow()
	stateInfo!ShortName = "WA"
	stateInfo!FullName = "Washington"
	stateInfo!Admission = #11/11/1889#
	stateInfo!Population = 5894121
	stateTable.Rows.Add(stateInfo)

	' ----- Add another record.
	stateInfo = stateTable.NewRow()
	stateInfo!ShortName = "MT"
	stateInfo!FullName = "Montana"
	stateInfo!Admission = #11/8/1889#
	stateInfo!Population = 902195
	stateTable.Rows.Add(stateInfo)

	' ----- Prove that the data arrived.
	MsgBox(stateTable.Rows.Count)       ' Displays "2"
	MsgBox(stateTable.Rows(0)!FullName) ' Displays "Washington"

ADO.NET defines the basic structures for tables, Read More >>

July 9, 2008 - Posted by Admin | database, programing, vb.net | , , , | No Comments Yet

No comments yet.

Leave a comment

You must be logged in to post a comment.