Home   Cover Cover Cover Cover

Adder: A Web Form With Button, Label and TextBox

From Section 6.2 of the book

Assume that we want to have a web page where the user can enter amounts of money that are added to an account balance. The page could look like this:


In order to do this we write an aspx page with web controls such as Label (for the balance), TextBox (for the money amount) and Button (to submit the form):

<%@ Page Language="C#" Inherits="AdderPage" Src="Adder.aspx.cs" %>
  <head> <title>Balance</title> </head>
    <form method="post" Runat="server">
      <b>Current balance:</b>
      <asp:Label ID="total" Text="0" Runat="server"/> Dollars<br><br>
      <asp:TextBox ID="amount" Runat="server"/>
      <asp:Button ID="ok" Text="Deposit" OnClick="ButtonClick" Runat="server" />

If the user clicks on the button, the method ButtonClick() is invoked. This method is declared in the following code-behind file:

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
public class AdderPage : Page {
  protected Label total;
  protected TextBox amount;
  protected Button ok;

  public void ButtonClick (object sender, EventArgs e) { 
    int totalVal = Convert.ToInt32(total.Text); 
    int amountVal = Convert.ToInt32(amount.Text); 
    total.Text = (totalVal + amountVal).ToString(); 

Note that the web controls are represented by protected fields in the code-behind class AdderPage.

Try it