Home   Cover Cover Cover Cover

User Controls

From Section 6.6.1 of the book

This example shows how a User Control can be built from several web controls. First of all, the web controls that should be combined are defined in an ascx file:

<%@ Control Inherits="MoneyFieldBase" Src="MoneyField.ascx.cs" %>

<asp:TextBox ID="amount" Runat="server" />

<asp:DropDownList ID="currency" AutoPostBack="true"
  OnSelectedIndexChanged="Select" Runat="server">
  <asp:ListItem Text="Euro" Value="1.0" Selected="true" />
  <asp:ListItem Text="US Dollar" Value="1.1489" />
  <asp:ListItem Text="Swiss Franc" Value="1.5725" />
  <asp:ListItem Text="British Pound" Value="0.6873" />

The script code for these web controls is implemented in a code-behind file:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;

public class MoneyFieldBase : UserControl {
  protected TextBox amount;
  protected DropDownList currency;
  private CultureInfo culture = new CultureInfo("en-US");
  public string Text {
    get { return amount.Text; }
    set { amount.Text = value; }
  public double OldFactor {
    get {return ViewState["factor"] == null ? 1 : (double)ViewState["factor"];}
    set {ViewState["factor"] = value; }

  public void Select(object sender, EventArgs arg) {
    try {
      double val = Convert.ToDouble(amount.Text, culture);
      double newFactor = Convert.ToDouble(currency.SelectedItem.Value, culture);
      double newVal = val / OldFactor * newFactor;
      amount.Text = newVal.ToString("f2", culture);
      OldFactor = newFactor;
    } catch (Exception) {
      amount.Text = "0";

Now the new User Control can be used one or several times on an aspx page:

<%@ Page Language="C#" %>
<%@ Register TagPrefix="my" TagName="MoneyField" Src="MoneyField.ascx" %>
  <form Runat="server">
    Amount 1: <my:MoneyField ID="field1" Text="100" Runat="server" /><br>
    Amount 2: <my:MoneyField ID="field2" Runat="server" />

Try it