Feb
21
Written by:
Steve Gray
2/21/2011 3:40 PM
This is a short example on how to create a DataTable dynamically, assign a primary key to it, and then how to update it
You can search a data table with or without a primary key, but if you don’t use the key you’ll get back an array of rows; in this case the single row is really what we need.
This code is very useful for submitting samples to vendors, you don’t have to fake data connections.
There is no error checking, this is just template code.
Code Snippet
- Function GetDataTable() As DataTable
- Dim oDT As New DataTable
- Dim oKeys(0) As DataColumn
- 'create a data table to use as our input source
-
- 'create columns
- Dim oCol As DataColumn = New DataColumn("order", System.Type.GetType("System.String"))
- oDT.Columns.Add(oCol)
- oKeys(0) = oCol
- oDT.Columns.Add(New DataColumn("salesperson", System.Type.GetType("System.String")))
- oDT.Columns.Add(New DataColumn("amount", System.Type.GetType("System.Double")))
- oDT.PrimaryKey = oKeys
-
- 'create the rows
- oDT.Rows.Add("ORD00100", "Bob@test.com", 1.23)
- oDT.Rows.Add("ORD00102", "Bob@test.com", 3.23)
- oDT.Rows.Add("ORD00104", "Sam@test.com", 2.23)
- oDT.Rows.Add("ORD00105", "Sam@test.com", 4.23)
-
- Return oDT
-
- End Function
-
- Sub updateDataTable(ByVal strOrder As String, ByVal dblAmount As Double)
- Dim oRow As DataRow
-
- '"order" is our primary key. Search the primary key for strOrder
- oRow = oDT.Rows.Find(strOrder)
-
- 'in the row found, set the Amount column
- oRow("amount") = dblAmount
-
- 'save
- oDT.AcceptChanges()
-
- End Sub
As always, I welcome your comments!