HOW TO: Implement a DataSet CREATE TABLE Helper Class in Visual C# .NET (325938)



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 Q325938
For a Microsoft Visual Basic .NET version of this article, see

325698 HOWTO: Implement a DataSet CREATE TABLE helper class in Visual Basic .NET

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 table from a comma-delimited list of field names and data types. This article includes a second method so that you can also specify the primary key columns.

The DataSetHelper class includes a DataSet member variable. Optionally, you can assign an existing DataSet object to the DataSet member variable. If the member variable points to a valid DataSet, any DataTable objects that the CreateTable method creates are added to the DataSet. In either case, the method call returns a reference to the DataTable object.

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 you need:
  • 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.
  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(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.
back to the top

CreateTable Method (Option 1)

This section contains the code for the main CreateTable method.

This is the sample calling convention for this CreateTable method:
DataTable dt = dsHelper.CreateTable("CT1", "Name String, ID Int32 Required, Field3 String Name + ID");
				
This code creates a new DataTable with a TableName of TestTable and three fields (Name, ID, and Field3). The Name and Field3 fields are of type System.String, and the ID field is a required field and is of type System.Int32. Field3 contains the result of the "Name + ID" expression.

Use the following syntax to specify fields in the field list:
fieldname datatype[ REQUIRED|expression], ...
				
  • The data types that are supported are any member of the System namespace, such as the Int32 or the String member. You cannot use language-specific data types, such as int or Integer. Also, do not specify the System namespace explicitly in the field list; this namespace is implied.
  • By default, all fields are optional. Add the word REQUIRED after the data type to disallow NULL values in the field.
  • The expression is any valid expression that the DataColumn class supports.
To call this CreateTable method, add the following method to the DataSetHelper class that you created in the "DataSetHelper Shell Class" section:
public DataTable CreateTable(string TableName, string FieldList)
{	
	DataTable dt = new DataTable(TableName);
	DataColumn dc;
	string[] Fields= FieldList.Split(',');    
	string[] FieldsParts;
	string Expression;
	foreach(string Field in Fields)
	{
		FieldsParts = Field.Trim().Split(" ".ToCharArray(), 3); // allow for spaces in the expression
		// add fieldname and datatype			
		if (FieldsParts.Length == 2)
		{	
			dc = dt.Columns.Add(FieldsParts[0].Trim(), Type.GetType("System." + FieldsParts[1].Trim(),true,true));
			dc.AllowDBNull = true;
		}
		else if (FieldsParts.Length == 3)  // add fieldname, datatype, and expression
		{
			Expression = FieldsParts[2].Trim();
			if (Expression.ToUpper() == "REQUIRED")
			{				
				dc = dt.Columns.Add(FieldsParts[0].Trim(), Type.GetType("System." + FieldsParts[1].Trim(), true, true));
				dc.AllowDBNull = false;
			}
			else
			{
				dc = dt.Columns.Add(FieldsParts[0].Trim(), Type.GetType("System." + FieldsParts[1].Trim(), true, true), Expression);
			}
		}
		else
		{
			throw new ArgumentException("Invalid field definition: '" + Field + "'.");
		}
	}
	if (ds != null) 
	{
	        ds.Tables.Add(dt);
	}
	return dt;
}
				
back to the top

CreateTable Method (Option 2)

This section contains the code for a second CreateTable method that is the same as the first method except that this code adds a comma-delimited key fields list. This method calls the first CreateTable method to create the DataTable, parses the key field list, and then sets the DataTable.PrimaryKey property.

This is the sample calling convention for this CreateTable method:
DataTable dt = dsHelper.CreateTable("CT2","Name String, ID Int32 Required, Field3 String Name + ID", "ID");
				
This code creates a new DataTable with a TableName of TestTable and three fields. In this code, the ID field is the primary key. You can specify more than one key field name (for example, ID and Name).

To call this CreateTable method, add the following method to the DataSetHelper class that you created in the "DataSetHelper Shell Class" section:
public DataTable CreateTable(string TableName, string FieldList , string KeyFieldList)
{
	DataTable dt = CreateTable(TableName, FieldList);
	string[] KeyFields = KeyFieldList.Split(',');
	if (KeyFields.Length > 0)
	{
		DataColumn[] KeyFieldColumns= new DataColumn[KeyFields.Length];								        int i;
		for (i = 1; i==KeyFields.Length-1 ; ++i)
		{
		        KeyFieldColumns[i] = dt.Columns[KeyFields[i].Trim()];
		}
		dt.PrimaryKey = KeyFieldColumns;	
	}
	return dt;  // You do not have to add to DataSet - The CreateTable call does that
}
				
back to the top

Test the Application

  1. Save and then compile the DataSetHelper class that you created in the previous sections.
  2. Follow these steps to create a new Visual C# Windows Application:
    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 to the Windows Form application.
  6. In the form designer, drag two Button controls and a DataGrid control from the toolbox to the form. Name the buttons btnCreate1 and btnCreate2. Keep the default name for the DataGrid control (DataGrid1).
  7. In the form code, add the following Imports statement to the top of the Code window:
    using System.Data
    					
  8. Add the following variable declarations to the form definition:
    	DataSet ds;
    	DataSetHelper dsHelper;
    					
  9. Add the following code to the Form.Load event:
            ds = new DataSet();
    	dsHelper = new DataSetHelper(ds);
    					
  10. Add the following code to the btnCreate1.Click event:
    	DataTable dt = dsHelper.CreateTable("CT1", "Name String, ID Int32 Required, Field3 String Name + ID");
    	dt.Rows.Add(new Object[] {"Jones", 4});
    	dt.Rows.Add(new Object[] {"Jones", 8});
    	dt.Rows.Add(new Object[] {"Thompson", 42});
    	dataGrid1.SetDataBinding(ds,"CT1");	
    					
  11. Add the following code to the btnCreate2.Click event:
    	DataTable dt = dsHelper.CreateTable("CT2","Name String, ID Int32 Required, Field3 String Name + ID", "ID");
    	dt.Rows.Add(new Object[] {"Tom Jones", 45});
    	dt.Rows.Add(new Object[] {"Will Smith", 58});
    	dt.Rows.Add(new Object[] {"Davey Jones", 84});
    	dt.Rows.Add(new Object[] {"Rob Thompson", 42});
    	dataGrid1.SetDataBinding(ds, "CT2");
    
    					
  12. Run the application, and then click each of the buttons. Notice that the DataGrid is populated with the tables and data from the code.

    NOTE: You can only click the 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.
back to the top

Enhancement Ideas

You can extend the parser so that you can specify a maximum length for string columns. For example, you can use the following syntax:
String(50)
				
Add a condition to check whether the data type starts with "String(". If it does, use the number to set the MaxLength property of the DataColumn object.

back to the top

Troubleshooting

  • The expression must not contain a comma, even if the comma is embedded in quotation marks. For example, the following expression is not valid:
    LastName+", "+FirstName
    					
    This is a limitation of the parsing technique that is used. You can use a more sophisticated parsing technique so that you can embed commas in quotation marks. To work around this limitation, add the problematic expression after the table is created.

  • 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.
back to the top

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