SUMMARY
This step-by-step article describes how to implement and how use a
DataSetHelper class that includes sample code to create a
DataTable objects from two or more related
DataTable definitions and to copy records that are sorted and filtered from the source
DataTable objects to the destination
DataTable.
To do this, you use the following public methods:
- CreateJoinTable
- InsertJoinInto
- SelectJoinInto
The
SelectJoinInto method calls the
CreateJoinTable and the
InsertJoinInto methods. You can also use a private helper method and data members to store the parsed field list.
The
DataSetHelper class includes a
DataSet member variable. Optionally, you can assign an existing
DataSet to the
DataSet member variable. If the member variable points to a valid
DataSet, any
DataTable objects that the
CreateJoinTable or the
SelectJoinInto method creates are added to the
DataSet. In either case, the method call returns a reference to the
DataTable object. The
InsertJoinInto method requires an existing target
DataTable and does not return anything.
For more information about
DataSet objects, click the article number below to view the article in the Microsoft Knowledge Base:
313485 INFO: Roadmap for ADO.NET DataSet, DataView, and DataViewManager Objects
back to the top
Requirements
The following list outlines the recommended hardware, software, network
infrastructure, and service packs that are required:
- Microsoft Windows XP, Windows 2000, or Windows NT 4.0 Service Pack 6a
- Microsoft Visual Studio .NET
This article assumes that you are familiar with the following topics:
- Visual Basic .NET syntax
- ADO.NET fundamentals and syntax
back to the top
DataSetHelper Shell Class
The code in this section declares the shell class to which all
DataSetHelper articles add methods and member variables.
- Start Visual Studio .NET.
- On the File menu, point to New, and then click Project.
- In the New Project dialog box, click Visual Basic Projects under Project Types, and then click Class Library under Templates.
- In the Name box, type DataSetHelper.
- Replace the class code with the following code:
Public Class DataSetHelper
Public ds As DataSet
Public Sub New(ByVal DataSet As DataSet)
ds = DataSet
End Sub
Public Sub New()
ds = Nothing
End Sub
End Class
You can use the two overloads for the constructor to create an instance of the class with or without a reference to a valid DataSet. For a class that contains a reference to a valid DataSet, the DataTable objects that the methods return are also added automatically to the DataSet.
back to the top
Field List Parser
This section contains the code for a field list parser. The parsed structure is used so that the
CreateJoinTable and the
InsertJoinInto methods do not have to reparse the field list. These methods must reparse the field list if they are called from the
SelectJoinInto method or from your own code. The parsed field list and the unparsed field list are stored in
Private member variables of the
DataSetHelper class.
- Add the following Private class definition in the DataSetHelper class that you created in the "DataSetHelper Shell Class" section:
Private Class FieldInfo
Public RelationName As String
Public FieldName As String ' source table field name
Public FieldAlias As String ' destination table field name
Public Aggregate As String
End Class
NOTE: This class is common to other DataSetHelper articles and contains some fields that this article does not use. - Add the following Private member variables to the class definition immediately after the DataSet declaration:
Private m_FieldInfo As ArrayList, m_FieldList As String
- Add the following Private method to the class definition. This method is the same as the method that is used in other DataSetHelper articles.
Private Sub ParseFieldList(ByVal FieldList As String, Optional ByVal AllowRelation As Boolean = False)
'
' Parses FieldList into FieldInfo objects and adds them to the m_FieldInfo private member
'
' FieldList syntax: [relationname.]fieldname[ alias],...
'
If m_FieldList = FieldList Then Exit Sub
m_FieldInfo = New ArrayList()
m_FieldList = FieldList
Dim Field As FieldInfo, FieldParts() As String, Fields() As String = FieldList.Split(",")
Dim I As Integer
For I = 0 To Fields.Length - 1
Field = New FieldInfo()
'
' Parse FieldAlias
'
FieldParts = Fields(I).Trim().Split(" ")
Select Case FieldParts.Length
Case 1
' to be set at the end of the loop
Case 2
Field.FieldAlias = FieldParts(1)
Case Else
Throw New ArgumentException("Too many spaces in field definition: '" & Fields(I) & "'.")
End Select
'
' Parse FieldName and RelationName
'
FieldParts = FieldParts(0).Split(".")
Select Case FieldParts.Length
Case 1
Field.FieldName = FieldParts(0)
Case 2
If Not AllowRelation Then _
Throw New ArgumentException("Relation specifiers not allowed in field list: '" & Fields(I) & "'.")
End If
Field.RelationName = FieldParts(0).Trim()
Field.FieldName = FieldParts(1).Trim()
Case Else
Throw New ArgumentException("Invalid field definition: '" & Fields(I) & "'.")
End Select
If Field.FieldAlias = "" Then Field.FieldAlias = Field.FieldName
m_FieldInfo.Add(Field)
Next
End Sub
back to the top
CreateJoinTable Method
This section contains the code for the
CreateJoinTable method.
This is the calling convention for the
CreateJoinTable method:
dt = dsHelper.CreateJoinTable("TestTable", ds.Tables!Employees, "FirstName FName,LastName LName,DepartmentEmployee.DepartmentName Department")
This call sample creates a new
DataTable with a
TableName of TestTable and three fields (FName, LName, and Department). These three fields have the same data type as the FirstName and the LastName fields in the Employees table and the DepartmentName field in the parent table that is accessed through the DepartmentEmployee
DataRelation object.
Use the following syntax to specify fields in the field list:
[relationname.]fieldname[ alias], ...
Note the following for this syntax:
- The ColumnName and the DataType properties are the only properties that are copied to the destination DataTable.
- The evaluated result is copied for fields that contain an expression.
- You can rename a field in the destination DataTable by specifying an alias name.
- The field list can contain a subset of field names that are listed in a different order than the order in the source DataTable. If the field list is blank, an exception is thrown.
- The DataRelation must relate to the parent tables. For example, if you want to create a table that combines fields of the Customers, the Employees, and the Orders tables, you must use the Orders table as the source table and then reference fields in the Customers and the Employees tables by means of relations.
To call the
CreateJoinTable method, add the following method to the
DataSetHelper class that you created in the "
DataSetHelper Shell Class" section:
Public Function CreateJoinTable(ByVal TableName As String, _
ByVal SourceTable As DataTable, _
ByVal FieldList As String) As DataTable
'
' Creates a table based on fields of another table and related parent tables
'
' FieldList syntax: [relationname.]fieldname[ alias][,[relationname.]fieldname[ alias]]...
'
If FieldList = "" Then
Throw New ArgumentException("You must specify at least one field in the field list.")
' Return CreateTable(TableName, SourceTable)
Else
Dim dt As New DataTable(TableName)
ParseFieldList(FieldList, True)
Dim Field As FieldInfo, dc As DataColumn
For Each Field In m_FieldInfo
If Field.RelationName = "" Then<BR/>
dc = SourceTable.Columns(Field.FieldName)
dt.Columns.Add(Field.FieldAlias, dc.DataType)
Else
dc = SourceTable.ParentRelations(Field.RelationName).ParentTable.Columns(Field.FieldName)
dt.Columns.Add(Field.FieldAlias, dc.DataType)
End If
Next
If Not ds Is Nothing Then ds.Tables.Add(dt)
Return dt
End If
End Function
back to the top
InsertJoinInto Method
This section contains code for the
InsertJoinInto method. The
InsertJoinInto method copies records that are sorted and filtered from the source table and related tables to the destination table. When you call the
ParseFieldList property, you can parse lists that were previously parsed, if these lists are available. If the field list is blank, an exception is thrown.
This is the calling convention for the
InsertJoinInto method:
dsHelper.InsertJoinInto(ds.Tables!TestTable, ds.Tables!Employees, "FirstName FName,LastName LName,DepartmentEmployee.DepartmentName Department", "EmployeeID<5", "BirthDate")
The call sample copies records from the Employees
DataTable (and the DepartmentName field of a related
DataTable) to the TestTable
DataTable, which is filtered on "EmployeeID<5" and is sorted by BirthDate.
NOTE: The filter and the sort expressions apply only to the source table and not to any related tables.
To call the
InsertJoinInto method, add the following method to the
DataSetHelper class that you created in the "
DataSetHelper Shell Class" section:
Public Sub InsertJoinInto(ByVal DestTable As DataTable, _
ByVal SourceTable As DataTable, _
ByVal FieldList As String, _
Optional ByVal RowFilter As String = "", _
Optional ByVal Sort As String = "")
'
' Copies the selected rows and columns from SourceTable and then inserts them to DestTable
' FieldList has same format as CreateJoinTable
'
If FieldList = "" Then
Throw New ArgumentException("You must specify at least one field in the field list.")
' InsertInto(DestTable, SourceTable, RowFilter, Sort)
Else
ParseFieldList(FieldList, True)
Dim Field As FieldInfo
Dim Rows() As DataRow = SourceTable.Select(RowFilter, Sort)
Dim SourceRow, ParentRow, DestRow As DataRow
For Each SourceRow In Rows
DestRow = DestTable.NewRow()
For Each Field In m_FieldInfo
If Field.RelationName = "" Then
DestRow(Field.FieldAlias) = SourceRow(Field.FieldName)
Else
ParentRow = SourceRow.GetParentRow(Field.RelationName)
DestRow(Field.FieldAlias) = ParentRow(Field.FieldName)
End If
Next
DestTable.Rows.Add(DestRow)
Next
End If
End Sub
back to the top
SelectJoinInto Method
This section contains the code for the
SelectJoinInto method. This method is a combination of the
CreateJoinTable and the
InsertJoinInto methods. The
SelectJoinInto method creates a new
DataTable based on existing
DataTable objects and copies records that are sorted and filtered into the new
DataTable.
This is the calling convention for the
SelectJoinInto method:
dt = dsHelper.SelectInto("TestTable", ds.Tables!Employees, "FirstName FName,LastName LName,DepartmentEmployee.DepartmentName Department", "EmployeeID<5", "BirthDate")
This sample call creates a
DataTable named TestTable with three fields. These three fields are based on the FirstName and the LastName fields of the Employees
DataTable and the DepartmentName field of the
DataTable that is referenced through the DepartmentEmployee
DataRelation. Then this sample copies records from the Employees
DataTable to the TestTable
DataTable, which is filtered on "EmployeeID<5" and is sorted by BirthDate.
NOTE: The filter and the sort expressions apply only to the source table and not to related tables.
To call the
SelectJoinInto method, add the following method to the
DataSetHelper class that you created in the "
DataSetHelper Shell Class" section:
Public Function SelectJoinInto(ByVal TableName As String, _
ByVal SourceTable As DataTable, _
ByVal FieldList As String, _
Optional ByVal RowFilter As String = "", _
Optional ByVal Sort As String = "") As DataTable
'
' Selects sorted and filtered values from one DataTable to another.
' With this code, you can specify relationname.fieldname in the FieldList to include fields from
' a parent table. The sort and the filter expressions apply only to the base table and not to related tables.
'
Dim dt As DataTable = CreateJoinTable(TableName, SourceTable, FieldList)
InsertJoinInto(dt, SourceTable, FieldList, RowFilter, Sort)
Return dt
End Function
back to the top
Test the Application
- Save and then compile the DataSetHelper class that you created in the previous sections.
- Follow these steps to create a new Visual Basic Windows Application:
- Start Visual Studio .NET.
- On the File menu, point to New, and then click Project.
- In the New Project dialog box, click Visual Basic Projects under Project Types, and then click Windows Application under Templates.
- In Solution Explorer, right-click the solution, and then click Add Existing Project. Add the DataSetHelper project.
- On the Project menu, click Add Reference.
- In the Add Reference dialog box, click the Projects tab, and then add a reference to the DataSetHelper project to the Windows Form application.
- In the form designer, drag three Button controls and a DataGrid control from the toolbox to the form. Name the buttons btnCreateJoin, btnInsertJoinInto, and btnSelectJoinInto. Keep the default name for the DataGrid control (DataGrid1).
- In the form code, add the following Imports statement to the top of the Code window:
Imports System.Data
- Add the following variable declarations to the form definition:
Dim ds As DataSet, dsHelper As DataSetHelper.DataSetHelper
- Add the following code to the Form.Load event:
ds = New DataSet()
dsHelper = New DataSetHelper.DataSetHelper(ds)
'
' Create source tables
'
Dim dt As New DataTable("Employees")
dt.Columns.Add("EmployeeID", GetType(Integer))
dt.Columns.Add("FirstName", GetType(String))
dt.Columns.Add("LastName", GetType(String))
dt.Columns.Add("BirthDate", GetType(DateTime))
dt.Columns.Add("JobTitle", GetType(String))
dt.Columns.Add("DepartmentID", GetType(Integer))
dt.Rows.Add(New Object() {1, "Tommy", "Hill", #12/31/1970#, "Manager", 42})
dt.Rows.Add(New Object() {2, "Brooke", "Sheals", #12/31/1977#, "Manager", 23})
dt.Rows.Add(New Object() {3, "Bill", "Blast", #5/6/1982#, "Sales Clerk", 42})
dt.Rows.Add(New Object() {1, "Kevin", "Kline", #5/13/1978#, "Sales Clerk", 42})
dt.Rows.Add(New Object() {1, "Martha", "Seward", #7/4/1976#, "Sales Clerk", 23})
dt.Rows.Add(New Object() {1, "Dora", "Smith", #10/22/1985#, "Trainee", 42})
dt.Rows.Add(New Object() {1, "Elvis", "Pressman", #11/5/1972#, "Manager", 15})
dt.Rows.Add(New Object() {1, "Johnny", "Cache", #1/23/1984#, "Sales Clerk", 15})
dt.Rows.Add(New Object() {1, "Jean", "Hill", #4/14/1979#, "Sales Clerk", 42})
dt.Rows.Add(New Object() {1, "Anna", "Smith", #6/26/1985#, "Trainee", 15})
ds.Tables.Add(dt)
dt = New DataTable("Departments")
dt.Columns.Add("DepartmentID", GetType(Integer))
dt.Columns.Add("DepartmentName", GetType(String))
dt.Rows.Add(New Object() {15, "Men's Clothing"})
dt.Rows.Add(New Object() {23, "Women's Clothing"})
dt.Rows.Add(New Object() {42, "Children's Clothing"})
ds.Tables.Add(dt)
ds.Relations.Add("DepartmentEmployee", ds.Tables!Departments.Columns!DepartmentID, ds.Tables!Employees.Columns!DepartmentID)
- Add the following code to the btnCreateJoin.Click event:
dsHelper.CreateJoinTable("EmpDept", ds.Tables!Employees, "FirstName FName,LastName LName,BirthDate,DepartmentEmployee.DepartmentName Department")
DataGrid1.SetDataBinding(ds, "EmpDept")
- Add the following code to the btnInsertJoinInto.Click event:
dsHelper.InsertJoinInto(ds.Tables!EmpDept, ds.Tables!Employees, "FirstName FName,LastName LName,BirthDate,DepartmentEmployee.DepartmentName Department", "JobTitle='Sales Clerk'", "DepartmentID")
DataGrid1.SetDataBinding(ds, "EmpDept")
- Add the following code to the btnSelectJoinInto.Click event:
dsHelper.SelectJoinInto("EmpDept2", ds.Tables!Employees, "FirstName,LastName,BirthDate BDate,DepartmentEmployee.DepartmentName Department", "JobTitle='Manager'", "DepartmentID")
DataGrid1.SetDataBinding(ds, "EmpDept2")
- Run the application, and then click each of the buttons. Notice that the DataGrid is populated with the tables and the data from the code.
NOTE: You can only click the btnCreateJoin and the btnSelectJoinInto buttons one time. If you click either of these buttons more than one time, you receive an error message that you are trying to add the same table two times. Additionally, you must click btnCreateJoin before you click btnInsertJoinInto; otherwise, the destination DataTable is not created. If you click the btnInsertJoinInto button multiple times, you populate the DataGrid with duplicate records.
back to the top
Enhancement Ideas
- The ColumnName and the DataType properties are the only properties that are copied to the destination DataTable. You can extend the CreateTable method to copy additional properties, such as the MaxLength property, or you can create new key columns.
- The Expression property is not copied; instead, the evaluated result is copied. Therefore, you do not have to add fields that are referenced by the expression to the destination table. Additionally, the destination column can appear earlier in the result list than any of the columns that this column depends on otherwise. You can modify the CreateTable method to copy the Expression (the InsertInto column ignores columns with an Expression), although this is subject to the limitations that are mentioned earlier in this paragraph.
- You can merge the functionality of the CreateJoinTable, the InsertJoinInto, and the SelectJoinInto methods into the CreateTable, the InsertInto, and the SelectInto methods. For additional information about the CreateTable, the InsertInto, and the SelectInto methods, click the article number below to view the article in the Microsoft Knowledge Base:
325683 HOWTO: Implement a DataSet SELECT INTO Helper Class in Visual Basic .NET
If you do not want to merge these methods, but if you have both sets of methods in a single class, you can enable the CreateJoinTable and the InsertJoinInto methods to handle an empty field list by removing the Throw statements and by uncommenting the calls to the CreateTable and the InsertInto methods in the following lines of code:
If FieldList = "" Then
Throw New ArgumentException("You must specify at least one field in the field list.")
' Return CreateTable(TableName, SourceTable)
-and-
If FieldList = "" Then
Throw New ArgumentException("You must specify at least one field in the field list.")
' InsertInto(DestTable, SourceTable, RowFilter, Sort)
back to the top
Troubleshooting
- The fieldname and the alias parts of the field list must comply with DataColumn naming conventions. The parser also restricts the names, in that the name must not contain a period (.), a comma (,), or a space ( ).
- If you click a button more than one time, the same table is added two times to the DataSet, which results in an exception. To work around this problem, you can add code to the test application to check whether a DataTable of the same name already exists. Alternatively, you can create the DataSetHelper class without a reference to a DataSet and then bind the DataGrid.DataSource property directly to the dt variable instead of by using the SetDataBinding method call.
- If the source table uses custom data types (that is, a class), you must add code to the InsertJoinInto method to perform a deep copy of the data. Otherwise, only a reference is copied.
back to the top