Microsoft KB Archive/325938

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

Article ID: 325938

Article Last Modified on 9/4/2003

-

APPLIES TO


 * Microsoft .NET Framework 1.1 Service Pack 1
 * Microsoft ADO.NET 1.1
 * Microsoft Visual C# .NET 2002 Standard Edition
 * Microsoft Visual C# .NET 2003 Standard Edition

-



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.

Click here to view the complete list of DataSetHelper articles

This article refers to the following Microsoft .NET Framework Class Library namespace:
 * System.Data

IN THIS TASK
SUMMARY
 * Requirements
 * DataSetHelper Shell Class
 * CreateTable Method (Option 1)
 * CreateTable Method (Option 2)
 * Test the Application
 * Enhancement Ideas
 * Troubleshooting



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.  Start Visual Studio .NET. On the File menu, point to New, and then click Project. In the New Project dialog box, click Visual C# 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 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(&quot;CT1&quot;, &quot;Name String, ID Int32 Required, Field3 String Name + ID&quot;); 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 &quot;Name + ID&quot; 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 &quot;DataSetHelper Shell Class&quot; 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(&quot; &quot;.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(&quot;System.&quot; + 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 == &quot;REQUIRED&quot;) {                              dc = dt.Columns.Add(FieldsParts[0].Trim, Type.GetType(&quot;System.&quot; + FieldsParts[1].Trim, true, true)); dc.AllowDBNull = false; }           else {               dc = dt.Columns.Add(FieldsParts[0].Trim, Type.GetType(&quot;System.&quot; + FieldsParts[1].Trim, true, true), Expression); }       }        else {           throw new ArgumentException(&quot;Invalid field definition: '&quot; + Field + &quot;'.&quot;); }   }    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(&quot;CT2&quot;,&quot;Name String, ID Int32 Required, Field3 String Name + ID&quot;, &quot;ID&quot;); 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 &quot;DataSetHelper Shell Class&quot; 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
 Save and then compile the DataSetHelper class that you created in the previous sections.</li> Follow these steps to create a new Visual C# Windows Application:  Start Visual Studio .NET.</li> On the File menu, point to New, and then click Project.</li> In the New Project dialog box, click Visual C# Projects under Project Types, and then click Windows Application under Templates.</li></ol> </li> In Solution Explorer, right-click the solution, and then click Add Existing Project. Add the DataSetHelper project.</li> On the Project menu, click Add Reference.</li> In the Add Reference dialog box, click the Projects tab, and then add a reference to the DataSetHelper project to the Windows Form application.</li> 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).</li>  In the form code, add the following Imports statement to the top of the Code window: using System.Data </li>  Add the following variable declarations to the form definition: DataSet ds; DataSetHelper dsHelper; </li>  Add the following code to the Form.Load event: ds = new DataSet; dsHelper = new DataSetHelper(ds); </li>  Add the following code to the btnCreate1.Click event: DataTable dt = dsHelper.CreateTable(&quot;CT1&quot;, &quot;Name String, ID Int32 Required, Field3 String Name + ID&quot;); dt.Rows.Add(new Object[] {&quot;Jones&quot;, 4}); dt.Rows.Add(new Object[] {&quot;Jones&quot;, 8}); dt.Rows.Add(new Object[] {&quot;Thompson&quot;, 42}); dataGrid1.SetDataBinding(ds,&quot;CT1&quot;); </li>  Add the following code to the btnCreate2.Click event: DataTable dt = dsHelper.CreateTable(&quot;CT2&quot;,&quot;Name String, ID Int32 Required, Field3 String Name + ID&quot;, &quot;ID&quot;); dt.Rows.Add(new Object[] {&quot;Tom Jones&quot;, 45}); dt.Rows.Add(new Object[] {&quot;Will Smith&quot;, 58}); dt.Rows.Add(new Object[] {&quot;Davey Jones&quot;, 84}); dt.Rows.Add(new Object[] {&quot;Rob Thompson&quot;, 42}); dataGrid1.SetDataBinding(ds, &quot;CT2&quot;);

</li> 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.</li></ol>

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 &quot;String(&quot;. If it does, use the number to set the MaxLength property of the DataColumn object.

back to the top

Troubleshooting
<ul> <li> 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+&quot;, &quot;+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.

</li> <li>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.</li></ul>

back to the top

Keywords: kbhowtomaster kbsystemdata KB325938

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.