In this article, we shall learn how to work with multiple results set using and SqlDataReader.
ADO.NET is a mechanism to communicate with the database. It allows us to work in connected (database connection is alive while the operation is performed) as well as disconnected architecture (database connection is closed and operation can be performed on the data).
Get hundreds of ASP.NET Tips and Tricks and ASP.NET Online training here.
In order to retrieve more than one result sets using Stored Procedure or multiple select statements in one go using
SqlDataReader, we can follow this approach.
Below is the GridView code on my ASPX Page
<asp:GridView ID="GridView1" runat="server" EnableViewState="false" />
<asp:GridView ID="GridView2" runat="server" EnableViewState="false" />
In above code snippet, we have two GridViews in which we shall bind both result sets.
string _connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
// get the connection
using (SqlConnection conn = new SqlConnection(_connStr))
// write the sql statement to execute
string sql = "SELECT AutoID, FirstName, LastName, Active FROM
PersonalDetail ORDER BY FirstName; " +
"SELECT AutoId, FileName FROM Files Order By FileName ASC";
// instantiate the command object to fire
using (SqlCommand cmd = new SqlCommand(sql, conn))
// in case of multiple result set you will not be able to specify the
// if so you will not be able to get the next result set from the
using (SqlDataReader reader = cmd.ExecuteReader())
// bind the first resultset
GridView1.DataSource = reader;
// bind the second resultset
GridView2.DataSource = reader;
In the code behind, we have executed two SQL statements (sql string variable has two SELECT statements separated by ";") in the
The first result set can be accessed by simply calling the reader object however to access the second result set, we need to explicitly call the
NextResult method of the reader object.
Notice that we will not be able to specify the
CommandBehavior.CloseConnection while executing the reader from the command object in this case (when the reader is returning two result sets), if so it throws following error while trying to access the next result set.
Exception Details: System.InvalidOperationException: Invalid attempt to call NextResult when reader is closed.
Hope this article was useful, do let me know your comment or feedback.
In case you are looking for returning multiple results set using
DataSet, use this article.
Stay tuned for many more articles and do not forget to refer these articles to your friend in need.
Thanks for reading.