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):

Adder.aspx
<%@ Page Language="C#" Inherits="AdderPage" Src="Adder.aspx.cs" %>
<html>
  <head> <title>Balance</title> </head>
  <body>
    <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" />
    </form>
  </body>
</html>

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

Adder.aspx.cs
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

   http://dotnet.jku.at/book/samples/6/Adder.aspx