HOW TO: Implement a DataSet SELECT INTO Helper Class in Visual C# .NET (326009)



The information in this article applies to:

  • Microsoft ADO.NET (included with the .NET Framework)
  • Microsoft ADO.NET (included with the .NET Framework 1.1)
  • Microsoft Visual C# .NET (2002)
  • Microsoft Visual C# .NET (2003)

This article was previously published under Q326009
For a Microsoft Visual Basic .NET version of this article, see 325683.

NOTE: This article is one of a series of DataSetHelper articles. You can merge the code in the DataSetHelper class that is listed in this article with the code that is provided in other DataSetHelper articles to make a single class with a more comprehensive feature set. This article refers to the following Microsoft .NET Framework Class Library namespace:
  • System.Data

IN THIS TASK

SUMMARY

This step-by-step article describes how to implement and how to use a DataSetHelper class that includes sample code to create a DataTable object from an existing DataTable definition and to copy records that are sorted and filtered from the source DataTable to the destination DataTable.

To do this, you use the following public methods:
  • CreateTable
  • InsertInto
  • SelectInto
The SelectInto method calls the InsertInto and the CreateTable 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 CreateTable or the SelectInto method create are added to the DataSet. In either case, the method call returns a reference to the DataTable object. The InsertInto 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

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 C# .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.
  1. Start Visual Studio .NET.
  2. On the File menu, point to New, and then click Project.
  3. In the New Project dialog box, click Visual C# Projects under Project Types, and then click Class Library under Templates.
  4. In the Name box, type DataSetHelper.
  5. Replace the class code with the following code:
    public class DataSetHelper
    {
        public DataSet ds;
    
        public DataSetHelper(ref DataSet DataSet)
        {
    	ds = DataSet;
        }
        public DataSetHelper()
        {
    	ds = null;
        }
    }
    						
    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.

    Additionally, make sure that you add the following code to the top of the code window in the DataSetHelper class:
    using System.Data; 
    					
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 CreateTable and the InsertInto methods do not have to reparse the field list. These methods must reparse the field list if they are called from the SelectInto 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.
  1. Add the following Private class definition in the DataSetHelper class that you created in the "DataSetHelper Shell Class" section:
    private class FieldInfo
    {
        public string RelationName;
        public string FieldName;	//source table field name
        public string FieldAlias;	//destination table field name
        public string Aggregate;
    }
    						
    NOTE: This class is common to other DataSetHelper articles and contains some fields that this article does not use.
  2. Add the following Private member variables to the class definition immediately after the DataSet declaration:
    private System.Collections.ArrayList m_FieldInfo; private string m_FieldList;
    					
  3. Add the following Private method to the DataSetHelper class definition. This method is the same as the method that is used in other DataSetHelper articles and supports an optional, extended syntax for the field list.
    private void ParseFieldList(string FieldList, bool AllowRelation)
    {
        /*
         * This code parses FieldList into FieldInfo objects and then 
         * adds them to the m_FieldInfo private member.
         * 
         * FieldList syntax:  [relationname.]fieldname[ alias], ...
        */ 
        if (m_FieldList == FieldList) return;
        m_FieldInfo = new System.Collections.ArrayList();
        m_FieldList = FieldList;
        FieldInfo Field; string[] FieldParts;
        string[] Fields=FieldList.Split(',');
        int i;
        for (i=0; i<=Fields.Length-1; i++)
        {
            Field=new FieldInfo();
            //Parse FieldAlias.
            FieldParts = Fields[i].Trim().Split(' ');
            switch (FieldParts.Length)
            {
                case 1:
                    //to be set at the end of the loop
                    break;
                case 2:
                    Field.FieldAlias=FieldParts[1];
                    break;
                default:
                    throw new Exception("Too many spaces in field definition: '" + Fields[i] + "'.");	                        
            }
            //Parse FieldName and RelationName.
            FieldParts = FieldParts[0].Split('.');
            switch (FieldParts.Length)
            {
                case 1: 
                    Field.FieldName=FieldParts[0];
                    break;
                case 2:
                    if (AllowRelation==false)
                        throw new Exception("Relation specifiers not permitted in field list: '" + Fields[i] + "'.");
                    Field.RelationName = FieldParts[0].Trim();
                    Field.FieldName=FieldParts[1].Trim();
                    break;
                default:
                    throw new Exception("Invalid field definition: " + Fields[i] + "'.");
            }
            if (Field.FieldAlias==null) 
                Field.FieldAlias = Field.FieldName;
            m_FieldInfo.Add (Field);
        }
    }
    					
back to the top

CreateTable Method

This section contains the code for the CreateTable method.

This is the calling convention for the CreateTable method:
dt = dsHelper.CreateTable("TestTable", ds.Tables["Employees"], "FirstName FName,LastName LName,BirthDate");
				
This call sample creates a new DataTable with a TableName of TestTable and three fields (FName, LName, and BirthDate). The three TestTable fields have the same data type as the FirstName, the LastName, and the BirthDate fields in the DataTable that is named Employees.

Use the following syntax to specify fields in the field list:
fieldname[ alias], ...
				
Note the following points for the calling convention and the 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 in the source DataTable. If the field list is blank, all of the fields are copied by using the DataTable.Clone method. In this case, because the destination DataTable must contain all of the fields of the source DataTable, the destination DataTable also contains fields with expressions.
To call the CreateTable method, add the following method to the DataSetHelper class that you created in the "DataSetHelper Shell Class" section:
public DataTable CreateTable(string TableName, DataTable SourceTable, string FieldList)
{
    /*
     * This code creates a DataTable by using the SourceTable as a template and creates the fields in the
     * order that is specified in the FieldList. If the FieldList is blank, the code uses DataTable.Clone().
    */ 
    DataTable dt; 
    if (FieldList.Trim() == "")
    {
        dt = SourceTable.Clone();
        dt.TableName = TableName;
    }
    else
    {
        dt = new DataTable(TableName);
        ParseFieldList(FieldList,false);
        DataColumn dc;
        foreach (FieldInfo Field in m_FieldInfo)
        {
            dc = SourceTable.Columns[Field.FieldName];
            dt.Columns.Add(Field.FieldAlias, dc.DataType);
        }
    }
    if (ds!=null)
        ds.Tables.Add(dt);
    return dt;
}
				
back to the top

InsertInto Method

This section contains code for the InsertInto method. This code copies records that are sorted and filtered from the source table to the destination table. This code copies only the fields in the destination table. When you call the ParseFieldList property, you can use a list that was previously parsed, if such a list is available. If the field list is blank, all of the fields are copied. Fields in the destination table that contain an expression are not copied.

This is the calling convention for the InsertInto method:
dsHelper.InsertInto(ds.Tables["TestTable"], ds.Tables["Employees"], "FirstName FName,LastName LName,BirthDate", "EmployeeID<5", "BirthDate") ;
				
This call sample copies records from the Employees DataTable to the TestTable DataTable, which is filtered on "EmployeeID<5" and is sorted by BirthDate.

To call the InsertInto method, add the following method to the DataSetHelper class that you created in the "DataSetHelper Shell Class" section:
public void InsertInto(DataTable DestTable, DataTable SourceTable, 
    string FieldList, string RowFilter, string Sort)
{
    // 
    // This code copies the selected rows and columns from SourceTable and inserts them into DestTable.
    // 
    ParseFieldList(FieldList, false);
    DataRow[] Rows = SourceTable.Select(RowFilter, Sort);
    DataRow DestRow;
    foreach(DataRow SourceRow in Rows)
    {
        DestRow = DestTable.NewRow();
        if (FieldList == "")
        {
            foreach(DataColumn dc in DestRow.Table.Columns)
            {
                if (dc.Expression == "")
                    DestRow[dc] = SourceRow[dc.ColumnName];
            }
        }
        else
        {
            foreach(FieldInfo Field in m_FieldInfo)
            {
                DestRow[Field.FieldAlias] = SourceRow[Field.FieldName];
            }
        }
        DestTable.Rows.Add(DestRow);
    }
}
				
back to the top

SelectInto Method

This section contains the code for the SelectInto method. This method is a combination of the CreateTable and the InsertInto methods. The SelectInto method creates a new DataTable based on an existing DataTable and copies the records that are sorted and filtered to the new DataTable.

This is the calling convention for the SelectInto method:
dt = dsHelper.SelectInto("TestTable", ds.Tables["Employees"], "FirstName FName,LastName LName,BirthDate", "EmployeeID<5", "BirthDate") ;
				
This call sample creates a DataTable that is named TestTable with three fields that are based on the FirstName, the LastName, and the BirthDate fields of the Employees DataTable. Then this sample copies records from the Employees DataTable to the TestTable DataTable, which is filtered on "EmployeeID<5" and is sorted by BirthDate.

To call the SelectInto method, add the following method to the DataSetHelper class that you created in the "DataSetHelper Shell Class" section:
public DataTable SelectInto(string TableName, DataTable SourceTable, 
    string FieldList, string RowFilter, string Sort)
{
    /*
     *  This code selects values that are sorted and filtered from one DataTable into another.
     *  The FieldList specifies which fields are to be copied.
    */ 
    DataTable dt = CreateTable(TableName, SourceTable, FieldList);
    InsertInto(dt, SourceTable, FieldList, RowFilter, Sort);
    return dt;    
}
				
back to the top

Test the Application

  1. Save and then compile the DataSetHelper class that you created in the previous sections.
  2. To create a new Visual C# Windows application, follow these steps:
    1. Start Visual Studio .NET.
    2. On the File menu, point to New, and then click Project.
    3. In the New Project dialog box, click Visual C# Projects under Project Types, and then click Windows Application under Templates.
  3. In Solution Explorer, right-click the solution, and then click Add Existing Project. Add the DataSetHelper project.
  4. On the Project menu, click Add Reference.
  5. In the Add Reference dialog box, click the Projects tab, and then add a reference to the DataSetHelper project in the Windows Form application.
  6. In the form designer, drag three Button controls and a DataGrid control from the toolbox to the form. Name the buttons btnCreate, btnInsertInto, and btnSelectInto. Keep the default name for the DataGrid control (DataGrid1).
  7. In the form code, add the following using statement to the top of the code window:
    using System.Data;
    					
  8. Add the following variable declarations to the form definition:
    DataSet ds; DataSetHelper.DataSetHelper dsHelper;
    					
  9. Add the following code to the Form1_Load event:
    ds = new DataSet();
    dsHelper = new DataSetHelper.DataSetHelper(ref ds);
    //Create source table.
    DataTable dt = new DataTable("Employees");
    dt.Columns.Add("EmployeeID",Type.GetType("System.Int32") );
    dt.Columns.Add("FirstName", Type.GetType("System.String"));
    dt.Columns.Add("LastName", Type.GetType("System.String"));
    dt.Columns.Add("BirthDate", Type.GetType("System.DateTime"));
    dt.Columns.Add("JobTitle", Type.GetType("System.String"));
    dt.Columns.Add("DepartmentID", Type.GetType("System.Int32"));
    dt.Rows.Add(new object[] {1, "Tommy", "Hill", new DateTime(1970, 12, 31),  "Manager", 42});
    dt.Rows.Add(new object[] {2, "Brooke", "Sheals", new DateTime(1977, 12, 31), "Manager", 23});
    dt.Rows.Add(new object[] {3, "Bill", "Blast", new DateTime(1982, 5, 6), "Sales Clerk", 42});
    dt.Rows.Add(new object[] {1, "Kevin", "Kline", new DateTime(1978, 5, 13), "Sales Clerk", 42});
    dt.Rows.Add(new object[] {1, "Martha", "Seward", new DateTime(1976, 7, 4), "Sales Clerk", 23});
    dt.Rows.Add(new object[] {1, "Dora", "Smith", new DateTime(1985, 10, 22), "Trainee", 42});
    dt.Rows.Add(new object[] {1, "Elvis", "Pressman", new DateTime(1972, 11, 5), "Manager", 15});
    dt.Rows.Add(new object[] {1, "Johnny", "Cache", new DateTime(1984, 1, 23), "Sales Clerk", 15});
    dt.Rows.Add(new object[] {1, "Jean", "Hill", new DateTime(1979, 4, 14), "Sales Clerk", 42});
    dt.Rows.Add(new object[] {1, "Anna", "Smith", new DateTime(1985, 6, 26), "Trainee", 15});
    ds.Tables.Add(dt);
    					
  10. Add the following code to the btnCreate_Click event:
    dsHelper.CreateTable("Emp2", ds.Tables["Employees"], 
        "FirstName FName,LastName LName,BirthDate");
    dataGrid1.SetDataBinding(ds, "Emp2");
    					
  11. Add the following code to the btnInsertInto_Click event:
    dsHelper.InsertInto(ds.Tables["Emp2"], ds.Tables["Employees"], 
        "FirstName FName,LastName LName,BirthDate", 
        "JobTitle='Sales Clerk'", "DepartmentID");
    dataGrid1.SetDataBinding(ds, "Emp2");
    					
  12. Add the following code to the btnSelectInto_Click event:
    dsHelper.SelectInto("Emp3", ds.Tables["Employees"], 
        "FirstName FName,LastName LName,BirthDate BDate", 
        "JobTitle='Manager'", "DepartmentID");
    dataGrid1.SetDataBinding(ds, "Emp3");
    					
  13. 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 btnCreate and the btnSelectInto 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 btnCreate before you click btnInsertInto; otherwise, the destination DataTable is not created. If you click the btnInsertInto 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.
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 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 InsertInto method to perform a deep copy of the data. Otherwise, only a reference will be copied.
back to the top

Modification Type:MajorLast Reviewed:9/4/2003
Keywords:kbHOWTOmaster kbSystemData KB326009 kbAudDeveloper