5.12. Exporting the Results of a Query to an Array

Problem

You need to export the results of a query to an array in a manner similar to the GetRows( ) method of the ADO Recordset.

Solution

Write a routine to mimic the functionality of the ADO Recordset’s GetRows( ) method.

The sample code contains an event handler and a method:

Go Button.Click

Sets up the sample by creating a DataTable containing the Orders table from Northwind. The GetRows( ) method in this solution is called to convert the DataTable into an array similar to one that is generated by the GetRows( ) method of the ADO Recordset. The contents of the array are displayed to a text box on the form.

GetRows( )

This method mimics the functionality of the GetRows( ) method of the ADO Recordset. First, an object array is created to hold the rows and columns in the table. The number of columns in the array is set to hold either all of the columns in the table or the subset of columns defined by the optional string array of column names. The number of rows in the table is set to hold either all of the rows in the table or the subset defined by the optional start row and row count arguments. The method then iterates over the collection of rows and columns in the table and sets the values in the array to the field values.

The C# code is shown in Example 5-14.

Example 5-14. File: AdoGetRowsForm.cs

// Namespaces, variables, and constants using System; using System.Configuration; using System.Text; using System.Data; using System.Data.SqlClient; ...

Get ADO.NET Cookbook now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.