Step 1: Design Page – SumOfDigits.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="SumOfDigits.aspx.cs" Inherits="SumOfDigits" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Sum of Digits - Real Time Example</title>
<style>
body {
font-family: Arial;
background-color: #f0f2f5;
margin: 50px;
}
.container {
width: 400px;
margin: auto;
background: white;
border-radius: 8px;
box-shadow: 0px 0px 10px #ccc;
padding: 20px;
}
h2 {
color: #1A2A80;
text-align: center;
}
.form-control {
width: 100%;
padding: 8px;
margin-top: 10px;
}
.btn {
background-color: #7A85C1;
color: white;
border: none;
padding: 10px 20px;
margin-top: 10px;
border-radius: 5px;
cursor: pointer;
}
.result {
font-weight: bold;
color: #333;
margin-top: 15px;
text-align: center;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div class="container">
<h2>Sum of Digits of a Number</h2>
<asp:Label ID="lblNumber" runat="server" Text="Enter a Number:"></asp:Label><br />
<asp:TextBox ID="txtNumber" runat="server" CssClass="form-control" placeholder="Example: 1234"></asp:TextBox><br />
<asp:Button ID="btnFindSum" runat="server" Text="Find Sum of Digits" CssClass="btn" OnClick="btnFindSum_Click" /><br />
<asp:Label ID="lblResult" runat="server" CssClass="result"></asp:Label>
</div>
</form>
</body>
</html>
Step 2: Backend Logic – SumOfDigits.aspx.cs
using System;
public partial class SumOfDigits : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnFindSum_Click(object sender, EventArgs e)
{
int number;
bool isValid = int.TryParse(txtNumber.Text.Trim(), out number);
if (!isValid || number < 0)
{
lblResult.Text = "Please enter a valid positive number.";
lblResult.ForeColor = System.Drawing.Color.Red;
return;
}
int sum = FindSumOfDigits(number);
lblResult.Text = $"The sum of digits of {number} is {sum}.";
lblResult.ForeColor = System.Drawing.Color.Green;
}
private int FindSumOfDigits(int num)
{
int sum = 0;
while (num > 0)
{
sum += num % 10; // Get the last digit
num /= 10; // Remove the last digit
}
return sum;
}
}
Real-Time Example Flow
Run the page
SumOfDigits.aspx.Enter a number like 1234.
Click “Find Sum of Digits”.
The result displays:
✅“The sum of digits of 1234 is 10.”
Explanation
| Component | Purpose |
|---|---|
| TextBox (txtNumber) | To input the number. |
| Button (btnFindSum) | Executes the logic on click. |
| FindSumOfDigits() | Uses % and / operators to extract and sum digits. |
| Label (lblResult) | Displays result dynamically. |
Sample Input / Output
| Input | Output |
|---|---|
| 123 | 6 |
| 987 | 24 |
| 5601 | 12 |
| 1000 | 1 |

Join the conversation! Your thoughts help the community grow.