Step 2. ASP.NET User Control
Using Visual Studio create a new user control called quotes.ascx. 
Edit the new User Control and create a ASP.NET Label called DailyQuotesLabel. The new User Control should look similar to this:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="quotes.ascx.cs" Inherits="controls_dailyquotes" %>
<asp:Label ID="DailyQuotesLabel" runat=server />
|
Next edit the code-behind for the User Control called quotes.ascx.cs. In the code-behind we create the database connection, execute the stored procedure and store the results the ASP.NET
Label DailyQuotesLabel.
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
public partial class controls_dailyquotes : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
string strResults = "";
string strConnection = ConfigurationSettings.AppSettings["DBConnect"];
SqlConnection objConnection = new SqlConnection(strConnection);
objConnection.Open();
SqlCommand objCommand = new SqlCommand("sp_dailyquotes_select", objConnection);
objCommand.CommandType = CommandType.StoredProcedure;
SqlDataReader objReader = objCommand.ExecuteReader();
while (objReader.Read() == true)
strResults += objReader["quote"] + "<br><b>" + objReader["author"] + "</b>";
DailyQuotesLabel.Text = strResults;
objReader.Close();
objConnection.Close();
}
}
|
Next open the quotes.aspx page and register the new User Control quote.ascx we created as QuotesUC and then reference
the control within the body of your page. Your page should look something like this:
<%@ Page Language="C#" CodeFile="quotes.aspx.cs" Inherits="quotes" Title="Quotes" %>
<%@ Register TagPrefix="QuotesUC" TagName="MyQuotes" Src="quotes.ascx" %>
<h2>They said it best:</h2>
<QuotesUC:MyQuotes ID="TheQuotes" runat=server />
|
Test Drive
Now that everything is seutp correctly you can try it out here quotes.aspx.
Each time you refresh the page you will see a new quote.
|