Retrieving ‘recordcount’ property in .NET

Spent a bit this morning wading through .NET documentation trying to find out how one retrieves the number of records returned from a query. Turns out it’s pretty simple. First you get your query rolling:

// get the connection string from settings
String cs = System.Configuration.ConfigurationSettings.AppSettings[“connectionString”].ToString();
// get a sql connection using the connection string
SqlConnection sqlcon = new SqlConnection(cs);
SqlDataAdapter adapter= new SqlDataAdapter(“select * from yourtable”, sqlcon);
DataSet dataset = new DataSet();
adapter.Fill(dataset,”mytable”);

At this point you’ve run the query and you have a DataSet which you can then loop over like any other collection, ie:

foreach (DataRow d in dataset.Tables[“mytable”].Rows)

or you can retrieve the number of rows:

DataRowCollection drc = dataset.Tables[“mytable”].Rows;
Console.WriteLine(“there are ” + drc.Count + ” rows in the query.”);

or even quicker like this:

Console.WriteLine(“there are ” + dataset.Tables[“mytable”].Rows.Count + ” rows in the query.”);

Back to work….

3 thoughts on “Retrieving ‘recordcount’ property in .NET”

  1. Great!!! It work for me. It’s good to see the row count some where. I was looking for it but no one knows about this.

    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *