Home   Cover Cover Cover Cover
 

Zusammengesetztes Steuerelement

Web-Seite, auf der das Steuerelement benutzt wird

../../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>

Deklaration des Steuerelements

../../solutions/6/TaxField.ascx
<%@ Control Inherits="TaxField" Src="TaxField.ascx.cs" %>
net amount
<asp:TextBox ID="net" Width="90" Font-Name="Courier" Font-Size="10"
  AutopostBack="true" OnTextChanged="SetGross" Runat="server"/>
gross amount
<asp:TextBox ID="gross" Width="90" Font-Name="Courier" Font-Size="10"
  AutopostBack="true" OnTextChanged="SetNet" Runat="server"/>

Hintergrundcode

../../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);
  }
}

Ausführung

Klicken Sie hier.