Introduction
Object-Oriented Programming (OOP) in C# allows us to model real-world entities as classes and objects.
In this example, we’ll create a Student class with fields, properties, and methods to store and display student details in an ASP.NET WebForms application.
Objective
Create a
Studentclass with fields like Name, Age, and Course.Add a method to display student details.
Access the class in a WebForm and show the details dynamically.
C# WebForms Real-Time Example
Step 1: ASPX Page (StudentDetails.aspx)
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="StudentDetails.aspx.cs" Inherits="WebApp.StudentDetails" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Student Class Example in C# WebForms</title>
</head>
<body>
<form id="form1" runat="server">
<div style="font-family: Arial; margin: 50px;">
<h2>Student Details Example</h2>
<asp:Label ID="Label1" runat="server" Text="Enter Name: "></asp:Label>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox><br /><br />
<asp:Label ID="Label2" runat="server" Text="Enter Age: "></asp:Label>
<asp:TextBox ID="txtAge" runat="server"></asp:TextBox><br /><br />
<asp:Label ID="Label3" runat="server" Text="Enter Course: "></asp:Label>
<asp:TextBox ID="txtCourse" runat="server"></asp:TextBox><br /><br />
<asp:Button ID="btnDisplay" runat="server" Text="Show Details" OnClick="btnDisplay_Click" /><br /><br />
<asp:Label ID="lblResult" runat="server" Font-Names="Consolas" Font-Size="Large"></asp:Label>
</div>
</form>
</body>
</html>
Step 2: Code-Behind (StudentDetails.aspx.cs)
using System;
namespace WebApp
{
public partial class StudentDetails : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnDisplay_Click(object sender, EventArgs e)
{
// Create an object of Student class and assign values
Student stud = new Student();
stud.Name = txtName.Text;
stud.Age = Convert.ToInt32(txtAge.Text);
stud.Course = txtCourse.Text;
// Display student details
lblResult.Text = stud.DisplayDetails();
}
}
// Step 3: Student class
public class Student
{
// Fields (Encapsulated using Properties)
public string Name { get; set; }
public int Age { get; set; }
public string Course { get; set; }
// Method to display student details
public string DisplayDetails()
{
return $"<b>Student Details:</b><br/>" +
$"Name: {Name}<br/>" +
$"Age: {Age}<br/>" +
$"Course: {Course}";
}
}
}

Join the conversation! Your thoughts help the community grow.