Aug 7, 2011

How to Add Two numbers using TextBox Control in asp.net

(i) .ASPX File Content
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Adding Two Number using TextBox Control Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table cellpadding="0" cellspacing="0" width="300px">
         <tr>
          <td><asp:Label ID="Label1" runat="server" Text="First Number"></asp:Label></td>
          <td><asp:TextBox ID="txtFirstNumber" runat="server"></asp:TextBox></td>
         </tr>
         <tr>
          <td><asp:Label ID="Label2" runat="server" Text="Second Number"></asp:Label></td>
          <td><asp:TextBox ID="txtSecondNumber" runat="server"></asp:TextBox></td>
         </tr>
         <tr>
         <td></td>
         <td><asp:Button ID="btnCalculate" runat="server" Text="Submit" OnClick="btnCalculate_Click" /></td>
         </tr>
         <tr>
          <td><asp:Label ID="Label3" runat="server" Text="Result is"></asp:Label></td>
          <td><asp:TextBox ID="txtResult" runat="server"></asp:TextBox> </td>
         </tr>
        </table>    
    </div>
    </form>
</body>
</html>
(ii) .ASPX.CS File Content
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page 
{
    //Declare variables
    int num1, num2, total = 0;
    protected void btnCalculate_Click(object sender, EventArgs e)
    {
        try
        {
            //Adding two numbers
            num1 = int.Parse(txtFirstNumber.Text.ToString().Trim());
            num2 = int.Parse(txtSecondNumber.Text.ToString().Trim());
            total = num1 + num2;
            txtResult.Text = total.ToString();
        }
        catch (Exception)
        {
            throw;
        }
    }
}
(iii) Output

1 comment: