Placing results from DataReader into an Array

Since the connection cannot be used until a DataReader has been closed, it is quite often necessary to read the results of a DataReader into an array, then close the DataReader, THEN you can process the data in the array while you use the connection for something else. I could only get this example to work with integers but not varchars (?).

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script language="C#" runat="server">
    void Page_Load(Object s, EventArgs e) {
        SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["con"]);
        SqlCommand cmd = new SqlCommand("CustomerByCountry",con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add(new SqlParameter("@publications",SqlDbType.Int)).Value = 3;
        //cmd.Parameters.Add(new SqlParameter("@country",SqlDbType.VarChar)).Value = "USA";
        ArrayList al = new ArrayList();
        SqlDataReader dr = cmd.ExecuteReader();
        while(dr.Read()) {
            object[] values = new object[dr.FieldCount];
        foreach(object[] row in al) {
            foreach(object column in row) {
                Response.Write(column.ToString() + "<br>");

Stored Procedure
CREATE PROCEDURE CustomerByCountry @publications int
FROM Customers
WHERE publications = @publications

You might also like...


Edward Tanguay Edward Tanguay updates his personal web site weekly with code, links, quotes and thoughts on web development. Sign up for the free newsletter.


Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“The greatest performance improvement of all is when a system goes from not-working to working.” - John Ousterhout