KnowDotNet NetRefactor

Creating a DataSet with Code

by William Ryan
Print this Article Discuss in Forums

As you undoubtedly are aware, ADO.NET allows you to create DataTables and DataSets.  If you aren't familiar with them, they are data objects which basically abstract real life data objects.  The DataTable is like a Table in your Database and the DataSet is like the database itself.  There are many uses for these objects and anytime you need to hold something, you can use one (although there are certianly lighter objects that you can use to hold a list of things).

In most instances, you declare a DataTable/DataSet and let a query fill it for you.  The table will get it's metadata from the Database so you don't need to add rows and columns on your own.  But if you need to create your own (or just want to for curiosity sake), here's a quick way to do it:


using System;
using System.Data;

namespace DictatePro
{
  
/// <summary>
  /// Summary description for patientDataSet.
  ///
  public class CodeBasedDataSet
   {
      
public patientDataSet(){}
      
public static DataSet CreateDataSet()
      {
                  
// Delcare a DataSet and Table
          DataSet ds;
          System.Data.DataTable dt;  
  
          ds =
new DataSet();
          dt =
new DataTable();

                  
// Declare your Columns - for brevity sake I went with the LameO
                  // constructors, but you can (and should) get more specific

          DataColumn LastName;
          DataColumn FirstName;
          DataColumn WT;
          DataColumn Desc;
        
                  
// Initialize the columns
          LastName =
new DataColumn("LastName");
          FirstName =
new DataColumn("FirstName");
          WT =
new DataColumn("WT");
          Desc =
new DataColumn("Desc");
        
                  
// Add them  to your DataTable
          dt.Columns.Add(LastName);
          dt.Columns.Add(FirstName);
          dt.Columns.Add(WT);
          dt.Columns.Add(Desc);
        
                  
// Add the DataTable to your DataSet
          ds.Tables.Add(dt);
        
// it's ready to run
        
return ds;
      }
   }
}


Now this is a pretty simple example and I don't have any data in it, but I could easily add rows inside here.  In most instances there wouldn't be much reason to do so, but that really depends on the circumstances and your design goals.

Writing Add-Ins for Visual Studio .NET
Writing Add-ins for Visual Studio .NET
by Les Smith
Apress Publishing