Executing a .NET Stored Procedure from an ASP.NET Page : CLR Database Objects « ADO.net Database « ASP.NET Tutorial






File: App_Code\RandomDataLayer.cs

using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Collections.Generic;

public class RandomDataLayer
{
    private static readonly string _connectionString;

    public List<String> GetRandomProducts()
    {        List<String> results = new List<String>();
        SqlConnection con = new SqlConnection(_connectionString);
        SqlCommand cmd = new SqlCommand("GetRandomRows", con);
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.AddWithValue("@rowsToReturn", 5);
        using (con)
        {
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            while (reader.Read())
                results.Add((string)reader["Title"]);
        }
        return results;
    }


    public static string GetRandomProduct()
    {
        string result = String.Empty;
        SqlConnection con = new SqlConnection(_connectionString);
        SqlCommand cmd = new SqlCommand("GetRandomRow", con);
        cmd.CommandType = CommandType.StoredProcedure;
        using (con)
        {
            con.Open();
            SqlDataReader reader = cmd.ExecuteReader();
            if (reader.Read())
                result = (string)reader["Title"];
        }
        return result;
    }

    static RandomDataLayer()
    {
        _connectionString = WebConfigurationManager.ConnectionStrings["Products"].ConnectionString;
    }
}

            

File: ShowRandomDataLayer.aspx

<%@ Page Language="C#" %>
<!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()
    {
        lblRandomProduct.Text = RandomDataLayer.GetRandomProduct();
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Show RandomDataLayer</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Random Product:
    <asp:Label
        id="lblRandomProduct"
        Runat="server" />

    <hr />

    <asp:GridView
        id="grdProducts"
        DataSourceID="srcProducts"
        Runat="server" />
    <asp:ObjectDataSource
        id="srcProducts"
        TypeName="RandomDataLayer"
        SelectMethod="GetRandomProducts"
        Runat="server" />
    </div>
    </form>
</body>
</html>








18.48.CLR Database Objects
18.48.1.Building Database Objects with the .NET Framework
18.48.2.Building a Data Access Layer with a User-Defined Type
18.48.3.Creating Stored Procedures with the .NET Framework
18.48.4.Executing a .NET Stored Procedure from an ASP.NET Page