|
|
User Controls
Web Page on which the User Control is used
/book/solutions/6/TaxFieldTest.aspx
<%@ Page Language="C#" %>
<%@ Register TagPrefix="my" TagName="TaxField" Src="TaxField.ascx" %>
<html>
<head>
<title>Sales sheet</title>
</head>
<body>
<h2>Sales</h2>
<form method="post" Runat="server">
<table border="1" cellpadding="3">
<tr>
<td>Computer</td>
<td><my:TaxField ID="computer" Rate="1,16" Runat="server" /></td>
</tr>
<tr>
<td>Screen</td>
<td><my:TaxField ID="screen" Rate="1,16" Runat="server" /></td>
</tr>
<tr>
<td>Printer</td>
<td><my:TaxField ID="printer" Rate="1,16" Runat="server" /></td>
</tr>
</table>
</form>
</body>
</html>
|
Declaration of the User Control
/book/solutions/6/TaxField.ascx
<%@ Control Inherits="TaxField" Src="TaxField.ascx.cs" %>
basic price
<asp:TextBox ID="net" Width="90" Font-Name="Courier" Font-Size="10"
AutopostBack="true" OnTextChanged="SetGross" Runat="server"/>
full price
<asp:TextBox ID="gross" Width="90" Font-Name="Courier" Font-Size="10"
AutopostBack="true" OnTextChanged="SetNet" Runat="server"/>
|
Code Behind
/book/solutions/6/TaxField.ascx.cs
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
public class TaxField : UserControl {
protected TextBox net;
protected TextBox gross;
double rate = 1.2; // default tax rate is 20%
//----- allows setting the tax rate in the user control
public string Rate {
get { return rate.ToString(); }
set { rate = Convert.ToDouble(value); }
}
//----- gross amount has been changed => change the net amount accordingly
public void SetNet(object sender, EventArgs e) {
double grossVal = Convert.ToDouble(gross.Text);
double netVal = grossVal / rate;
net.Text = String.Format("{0, 10:f2}", netVal);
gross.Text = String.Format("{0, 10:f2}", grossVal);
}
//----- net amount has been changed => change the gross amount accordingly
public void SetGross(object sender, EventArgs e) {
double netVal = Convert.ToDouble(net.Text);
double grossVal = netVal * rate;
net.Text = String.Format("{0, 10:f2}", netVal);
gross.Text = String.Format("{0, 10:f2}", grossVal);
}
}
|
Try it
Click here.
|