Mada za sehemu hiiWorking with IDE and event-driven languageMada 2
- Performing exploration of features and tools of the event-driven language IDE
- Creating basic programs using event-driven language
Event-Driven Programming: Creating Basic Programs
Event-driven programming is a programming pattern where the flow of a program is determined by events such as user actions (clicks, key presses), sensor outputs, or messages from other programs. Instead of running in a strict sequential order, an event-driven program waits for events to occur and then executes specific code called event handlers. This method is widely used in Graphical User Interface (GUI) applications to make programs more interactive and responsive to user input.
Before creating event-driven programs, you need to understand the Visual Studio development environment and basic C# programming concepts.
Creating a New C# Console Application
- Open Visual Studio
- Click File → New → Project
- Select C#: Console App (.NET Framework)
- Enter a project name (e.g., FormThree) and choose a save location
- Click Create
Displaying Output
The Console.WriteLine() command is used to display text on the screen.
static void Main(string[] args)
{
Console.WriteLine("Welcome to C# Programming!");
}
Variables and Data Types
Variables are containers for storing data. C# supports several data types:
| Type | Description | Example |
|---|---|---|
int | Whole numbers | int age = 15; |
double | Decimal numbers | double price = 2500.50; |
bool | True or false | bool isStudent = true; |
char | Single character | char grade = 'A'; |
string | Text | string name = "Amina"; |
Syntax: type variableName = value;
int age = 15;
string name = "Juma";
double height = 1.65;
bool isPresent = true;
Getting User Input
The Console.ReadLine() command receives input from the user.
Console.WriteLine("Enter your name:");
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name);
If-Else Statement
The if-else statement executes different blocks of code based on whether a condition is true or false.
if (condition)
{
// Code to execute if condition is true
}
else
{
// Code to execute if condition is false
}
Example: Checking if a number is positive
int number = 10;
if (number > 0)
{
Console.WriteLine("The number is positive.");
}
else
{
Console.WriteLine("The number is not positive.");
}
For Loop
A for loop is used when the number of iterations is known in advance.
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Iteration: " + i);
}
While Loop
A while loop continues as long as a condition is true.
int count = 1;
while (count <= 5)
{
Console.WriteLine("Count: " + count);
count++;
}
An array is a collection of elements of the same data type, stored under a single variable name.
Declaring Arrays
// Method 1: Declare size first
int[] marks = new int[3];
marks[0] = 85;
marks[1] = 90;
marks[2] = 78;
// Method 2: Initialize with values
string[] fruits = { "Mango", "Banana", "Papaya", "Orange" };
Accessing Array Elements
Array indices start at 0. To access the second element of the fruits array:
Console.WriteLine(fruits[1]); // Output: Banana
Looping Through an Array
int[] numbers = { 10, 20, 30 };
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine(numbers[i]);
}
A method is a block of code that performs a specific task. Methods help organize and reuse code.
User-Defined Methods
static void GreetUser()
{
Console.WriteLine("Hello, welcome to Form Three!");
}
static void Main(string[] args)
{
GreetUser(); // Calling the method
}
Methods with Parameters and Return Values
static int CalculateTotal(int math, int english, int science)
{
return math + english + science;
}
static void Main(string[] args)
{
int total = CalculateTotal(85, 90, 78);
Console.WriteLine("Total marks: " + total);
}
Recursive Methods
A recursive method calls itself to solve a problem by breaking it into smaller parts.
static int Factorial(int n)
{
if (n <= 1)
return 1; // Base case
else
return n * Factorial(n - 1); // Recursive case
}
Windows Forms (WinForms) is a GUI framework that allows you to create desktop applications with buttons, text boxes, labels, and other visual controls.
Creating a Windows Forms Project
- Open Visual Studio
- File → Create a new project
- Select C#: Windows Forms App (.NET Framework)
- Enter a project name (e.g., MyFirstApp)
- Click Create
A blank form (Form1) will appear where you can add controls.
Adding Controls to a Form
Use the Toolbox panel to drag and drop controls onto the form:
- Label: Displays text (e.g., "Enter your name:")
- TextBox: Allows user input
- Button: Triggers an action when clicked
- ListView: Displays a list of items
Setting Control Properties
Select a control and use the Properties window to change properties like:
Text: The text displayed on the controlName: The programmatic name used in codeSize: Width and height
Event-driven programs respond to user actions through event handlers.
Button Click Event
When a user clicks a button, the Click event is triggered.
Step 1: Double-click the button to generate the event handler
Step 2: Add code to handle the event
private void button1_Click(object sender, EventArgs e)
{
string name = textBox1.Text;
MessageBox.Show("Hello, " + name + "!", "Welcome");
}
Handling Empty Input
private void button1_Click(object sender, EventArgs e)
{
string name = textBox1.Text;
if (string.IsNullOrWhiteSpace(name))
{
MessageBox.Show("Please enter your name.", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
MessageBox.Show("Welcome, " + name + "!", "Greeting",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
TextChanged Event
The TextChanged event fires when the text in a TextBox changes. This can be used to enable/disable a button based on input.
private void textBox1_TextChanged(object sender, EventArgs e)
{
// Enable button only when text is entered
button1.Enabled = !string.IsNullOrWhiteSpace(textBox1.Text);
}
KeyDown Event (Keyboard Input)
Handle the Enter key to trigger button click from the keyboard.
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
button1_Click(sender, e); // Simulate button click
}
}
Mouse Events
Handle mouse movements to change button appearance.
private void button1_MouseHover(object sender, EventArgs e)
{
button1.BackColor = System.Drawing.Color.LightBlue;
}
private void button1_MouseLeave(object sender, EventArgs e)
{
button1.BackColor = System.Drawing.Color.LightGray;
}
This example creates a form that greets the user by name.
Design:
- Label: "Enter your name:"
- TextBox: For name input
- Button: "Submit"
Code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string name = textBox1.Text.Trim();
if (string.IsNullOrWhiteSpace(name))
{
MessageBox.Show("Please enter your name.", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
MessageBox.Show("Mambo, " + name + "! Karibu sana.", "Welcome",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
button1_Click(sender, e);
}
}
}
How it works:
- User enters their name in the TextBox
- User clicks Submit or presses Enter
- The code checks if the input is empty
- If empty, an error message appears
- If valid, a greeting message box appears
| Control | Event | When it occurs |
|---|---|---|
| Button | Click | Button is clicked |
| TextBox | TextChanged | Text content changes |
| TextBox | KeyDown | Keyboard key is pressed |
| Button | MouseHover | Mouse hovers over button |
| Button | MouseLeave | Mouse leaves button area |
| Form | Load | Form is first displayed |
In Tanzania, event-driven programming is used to create desktop applications for small businesses such as shops in Kariakoo or local supermarkets. For example, a shop owner in Dar es Salaam could use a simple Windows Forms application with buttons to record sales of rice or cooking oil, update inventory when items are sold, and generate daily sales reports — all by clicking buttons rather than typing commands, making the system easy to use even for staff with limited computer skills.
Jinsi utakavyotathminiwaTathmini ya mchakato · Tathmini ya matokeo · Tathmini ya maarifa
Tathmini ya mchakato
The student should be able to:
- Write and execute basic event-driven programs in an IDE.
Tathmini ya matokeo
Basic programs principled on event-driven programming paradigm are created.
Tathmini ya maarifa
Methods used: The trainee should explain how to:
- Use an IDE to create event-driven applications.
- Design and implement event-driven programs that respond to user inputs.
Principles: The student should explain the principle of:
- Understanding the role of event listeners, callbacks, and triggers in creating responsive applications.
Theories: The trainee should explain: The trainee should explain:
- How events are queued and processed in sequence to handle asynchronous user interactions.
- The phases of event propagation and their impact on event handling.
Circumstantial knowledge:
Detailed knowledge about:
- Common challenges in using IDEs for event-driven programming and how to overcome them.
Swali
Which C# data type should be used to store a student's age (a whole number)?
Ingia ili kuwasilisha jibu lako na lihesabiwe katika umahiri wako.
Ingia ili kufanya mazoeziMwalimu
Umekwama? Niulize chochote kuhusu mada hii.
Ingia ili kumuuliza Mwalimu wa AI wa Sonza kuhusu swali hili.
Ingia ili kuulizaMajadiliano
Hakuna maswali bado