Working with Multiple Active Resultsets : DataReader « ADO.net Database « ASP.NET Tutorial






File: ShowMARS.aspx


<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    void Page_Load()
    {
        if (!Page.IsPostBack)
            BuildTree();
    }

    void BuildTree()
    {
        string connectionString = @"MultipleActiveResultSets=True;"
            + @"Data Source=.\SQLExpress;Integrated Security=True;"
            + @"AttachDBFileName=|DataDirectory|MyDatabase.mdf;User Instance=True";
        SqlConnection con = new SqlConnection(connectionString);

        string cmdCategoriesText = "SELECT Id,Name FROM ProductCategories";
        SqlCommand cmdCategories = new SqlCommand(cmdCategoriesText, con);

        string cmdProductsText = "SELECT Title FROM Products "
            + "WHERE CategoryId=@CategoryID";
        SqlCommand cmdProducts = new SqlCommand(cmdProductsText, con);
        cmdProducts.Parameters.Add("@CategoryId", SqlDbType.Int);

        using (con)
        {
            con.Open();
            SqlDataReader categories = cmdCategories.ExecuteReader();
            while (categories.Read())
            {
                int id = categories.GetInt32(0);
                string name = categories.GetString(1);
                TreeNode catNode = new TreeNode(name);
                TreeView1.Nodes.Add(catNode);

                cmdProducts.Parameters["@CategoryId"].Value = id;
                SqlDataReader products = cmdProducts.ExecuteReader();
                while (products.Read())
                {
                    string title = products.GetString(0);
                    TreeNode productNode = new TreeNode(title);
                    catNode.ChildNodes.Add(productNode);
                }
                products.Close();
            }
        }
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Show MARS</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    <asp:TreeView
        id="TreeView1"
        Runat="server" />

    </div>
    </form>
</body>
</html>








18.24.DataReader
18.24.1.Using the DataReader Object
18.24.2.Iterating Through A DataReader
18.24.3.Create DataReader object from SqlCommand
18.24.4.List Binding DataReader
18.24.5.Returning Multiple Resultsets
18.24.6.Working with Multiple Active Resultsets