Write an ASP.Net program to accept a number from the user in a textbox control and throw an exception if the number is not a perfect number. Assume suitable controls on the web form.

Answer:

Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication5.WebForm1" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2>Perfect Number Checker</h2>
        <label for="Label1">Enter a number:</label>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
        <asp:Button ID="Button1" runat="server" Text="Check" OnClick="btnCheck_Click" /><br />
        <asp:Label ID="Label2" runat="server" ForeColor="Red"></asp:Label>
          </div>
    </form>
</body>
</html>
Default.aspx.cs
using System;
using System.Web.UI;

namespace WebApplication5
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
         protected void btnCheck_Click(object sender, EventArgs e)
        {
            try
            {
                int number = int.Parse(TextBox1.Text);
                
                if (IsPerfectNumber(number))
                {
                    Label2.Text = number + " is a perfect number!";
                }
                else
                {
                    throw new Exception(number + " is a not perfect number!");
                }
            }
            catch (Exception ex)
            {
                Label2.Text = ex.Message;
            }
        }
        private bool IsPerfectNumber(int number)
        {
            if (number <= 0)
                return false;

            int sum = 0;
            for (int i = 1; i <= number / 2; i++)
            {
                if (number % i == 0)
                {
                    sum += i;
                }
            }

            return sum == number;
        }
    }
}
Scroll to Top