Learn ASP.NET Web Forms, ASP.NET MVC, HTML5 and jQuery! Intensive courses for professional developers. Small batches, real world examples, convenient weekend timings. Conducted by Bipin Joshi in Thane. Registration open. Read more details here.

<%@ Page %>

Obtaining No. Of Record Returned From DataReader

Introduction

DataReader allows forwardonly and readonly data access. Many times we need to know the number of records returned after firing a SELECT query. DataReader do not offer this functionality. We can, however, use some trick to quickly and efficiently get this data. This How To is intended to show you just that.

Executing Batch Queries

The Command object can be used to fire batch of queries instead of single query. In this case we can execute action as well as select queries together. We can then call ExecuteReader method of the Command object. There can be multiple result sets obtained and those can be navigated using NextResult method of DataReader. Following code snippet shows how it works:
Dim cnn As New SqlConnection(Global.GetConnectionString)
Dim cmd As New SqlCommand()
Dim dr As SqlDataReader
cnn.Open()
cmd.CommandText = "select count(*) from employees;
select * from employees"
cmd.Connection = cnn

dr = cmd.ExecuteReader

dr.Read()
Label1.Text = dr.GetValue(0)
dr.NextResult()
DataGrid1.DataSource = dr
DataGrid1.DataBind()
Here, we have first declared objects of connection, command and DataReader. Note how the CommandText property of the command object is set to two SELECT queries separated by a ";". Next, the Command is executed and the output is assigned to DataReader. The DataReader contains two result sets matching our queries. First query gives us the number of records. The NextResult method shifts to the next result set and we can bind the actual data with the DataGrid.

I hope you must have find the article useful. See you soon.


Bipin Joshi is a blogger, author, IT trainer and a Kundalini Yogi who writes about apparently unrelated topics - Yoga & technology! Bipin has been programming since 1995 and is working with .NET framework ever since its inception. He is an internationally published author and has authored or co-authored more than half a dozen books and numerous articles on .NET technologies. He has also penned a few books on Yoga. Bipin was also a Microsoft MVP for six consecutive years. You can read more about him here. To know more about his training programs go here.

Stay updated : Twitter  Facebook  Google+  LinkedIn



Tags : ADO.NET Data Access SQL Server
Posted On : 08 Jun 2002
Current Rating :
Rate this article :


This page is protected by copyright laws. Copying in any form is strictly prohibited. For Copyright notice and legal terms of use click here.

Protected by Copyscape



Copyright (C) bipinjoshi.net. All rights reserved.
Contact Us
Read Copyright & Terms Of Use
Hosted By DiscountASP.net