Click here to Skip to main content
Licence Ms-PL
First Posted 27 May 2005
Views 93,407
Bookmarked 38 times

Simplest code to convert an ADO.NET DataTable to an ADODB.Recordset

By | 27 May 2005 | Article
Simple C# code to convert an ADO.NET (System.Data) DataTable to an ADODB Recordset.
 
Part of The SQL Zone sponsored by
See Also

Introduction

When working with a legacy ASP application, you might want to convert the core business objects to .NET class libraries while still allow the use of existing ASP pages. If those pages are based on manipulating ADODB Recordsets, it can be a real pain to expose them as an ADO.NET DataTable.

The existing examples I've seen are oriented around generating a full-fidelity replica of the DataTable which allows updates. In many situations, this is not needed and the added burden and fragility of these solutions is not warranted.

This article is a quick code snippet that shows what I believe is the simplest possible way to handle the conversion from an ADO.NET DataTable to an ADODB.Recordset, which can then be handled as if it was still coming from the older middleware component.

The Code

There are two functions, designed to be include as static members of some helper class. The main function is simple:

static public ADODB.Recordset ConvertToRecordset(DataTable inTable)
{
    ADODB.Recordset result = new ADODB.Recordset();
    result.CursorLocation = ADODB.CursorLocationEnum.adUseClient;

    ADODB.Fields resultFields = result.Fields;
    System.Data.DataColumnCollection inColumns = inTable.Columns;

    foreach (DataColumn inColumn in inColumns)
    {
        resultFields.Append(inColumn.ColumnName
            , TranslateType(inColumn.DataType)
            , inColumn.MaxLength
            , inColumn.AllowDBNull ? ADODB.FieldAttributeEnum.adFldIsNullable : 
                                     ADODB.FieldAttributeEnum.adFldUnspecified
            , null);
    }

    result.Open(System.Reflection.Missing.Value
            , System.Reflection.Missing.Value
            , ADODB.CursorTypeEnum.adOpenStatic
            , ADODB.LockTypeEnum.adLockOptimistic, 0);

    foreach (DataRow dr in inTable.Rows)
    {
        result.AddNew(System.Reflection.Missing.Value, 
                      System.Reflection.Missing.Value);

        for (int columnIndex = 0; columnIndex < inColumns.Count; columnIndex++)
        {
            resultFields[columnIndex].Value = dr[columnIndex];
        }
    }

    return result;
}

A helper function (which can easily be extended) maps the .NET data types to the correct ADODB field type enumeration.

static ADODB.DataTypeEnum TranslateType(Type columnType)
{
    switch (columnType.UnderlyingSystemType.ToString())
    {
        case "System.Boolean":
            return ADODB.DataTypeEnum.adBoolean;

        case "System.Byte":
            return ADODB.DataTypeEnum.adUnsignedTinyInt;

        case "System.Char":
            return ADODB.DataTypeEnum.adChar;

        case "System.DateTime":
            return ADODB.DataTypeEnum.adDate;

        case "System.Decimal":
            return ADODB.DataTypeEnum.adCurrency;

        case "System.Double":
            return ADODB.DataTypeEnum.adDouble;

        case "System.Int16":
            return ADODB.DataTypeEnum.adSmallInt;

        case "System.Int32":
            return ADODB.DataTypeEnum.adInteger;

        case "System.Int64":
            return ADODB.DataTypeEnum.adBigInt;

        case "System.SByte":
            return ADODB.DataTypeEnum.adTinyInt;

        case "System.Single":
            return ADODB.DataTypeEnum.adSingle;

        case "System.UInt16":
            return ADODB.DataTypeEnum.adUnsignedSmallInt;

        case "System.UInt32":
            return ADODB.DataTypeEnum.adUnsignedInt;

        case "System.UInt64":
            return ADODB.DataTypeEnum.adUnsignedBigInt;

        case "System.String":
        default:
            return ADODB.DataTypeEnum.adVarChar;
    }
}

Gotchas

  • You have to define the fields in the Recordset before you call the Open method or ADODB will give you an error.
  • This is a disconnected Recordset, so it cannot be used to update a table without further handling.
  • It only copies over the "current" values of the columns.
  • It copies all the rows, so be careful with large row-sets.

Other Articles

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)

About the Author

Marc Brooks

Web Developer

United States United States

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Question'Sort' property doesn't work for the converted Recordset Pinmemberronnie_bleum19:46 14 Oct '10  
GeneralMethod's type signature is not Interop compatible Pinmember_Matt_Wilkinson_6:12 8 Apr '10  
GeneralRe: Method's type signature is not Interop compatible PinmemberMarc Brooks13:42 8 Apr '10  
GeneraladVarChar becomes adLongVarChar PinmemberChad Jones10:13 29 Jul '09  
GeneralRe: adVarChar becomes adLongVarChar PinmemberMarc Brooks11:14 29 Jul '09  
GeneralRe: adVarChar becomes adLongVarChar PinmemberChad Jones11:24 29 Jul '09  
GeneralThanx! [modified] PinmemberDennis Betten13:57 13 Mar '08  
GeneralError in parsing a TIME column Pinmemberfiwi463pfa23:08 1 Apr '07  
GeneralRe: Error in parsing a TIME column PinmemberTim McCurdy9:37 19 Sep '07  
Generaladodb to ado.net Pinmembersmurfnz12:12 16 Jan '07  
General"System.byte[]" Pinmemberjwcarroll5:22 21 Sep '06  
GeneralFix Pinmemberjwcarroll5:29 21 Sep '06  
GeneralOne more thing... Pinmemberjwcarroll5:37 21 Sep '06  
GeneralRe: One more thing... PinmemberTim McCurdy9:40 19 Sep '07  
GeneralGreat article PinmemberDummyDUmb9:11 8 Sep '06  
GeneralRe: Great article PinmemberMarc Brooks9:30 8 Sep '06  
GeneralProblem AddNew Pinmemberrbarzallo7:02 17 May '06  
GeneralRe: Problem AddNew Pinmemberrbarzallo7:39 17 May '06  
GeneralRe: Problem AddNew PinmemberTim McCurdy9:41 19 Sep '07  
GeneralRe: Problem AddNew PinmemberCleber L.1:10 14 Dec '09  
GeneralFunction to convert ADODB.DataTypeEnum to System.Type PinmemberMichael Freidgeim16:37 12 Nov '05  
I have a complimentary function to your TranslateType that converts ADODB.DataTypeEnum to System.Type .
See FromAdoDbType function in my post
Fill Dataset with rows in a specified range from ADODB.Recordset[^]
 
Michael Freidgeim.
Blog: http://geekswithblogs.net/mnf/
GeneralError trying example PinsussJonBrune10:21 12 Oct '05  
GeneralRe: Error trying example PinmemberFranck Quintana11:49 8 Nov '05  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120529.1 | Last Updated 27 May 2005
Article Copyright 2005 by Marc Brooks
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid