0% found this document useful (0 votes)
7 views

C#Mod3and4 1

The document provides a comprehensive overview of delegates, exception handling, custom exceptions, event handling, and ADO.NET architecture in C#. It explains the steps to create and use delegates, including multicast delegates, and details exception handling mechanisms with code examples for handling multiple exceptions and creating custom exceptions. Additionally, it describes ADO.NET's architecture, including connected and disconnected data access, and outlines key features and data retrieval methods using DataReader and DataAdapter.

Uploaded by

karthikjyekkar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

C#Mod3and4 1

The document provides a comprehensive overview of delegates, exception handling, custom exceptions, event handling, and ADO.NET architecture in C#. It explains the steps to create and use delegates, including multicast delegates, and details exception handling mechanisms with code examples for handling multiple exceptions and creating custom exceptions. Additionally, it describes ADO.NET's architecture, including connected and disconnected data access, and outlines key features and data retrieval methods using DataReader and DataAdapter.

Uploaded by

karthikjyekkar
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Module-3

a) Explain the steps involved in creating and using delegates in C# program. Also
provide an example of a multicast delegate and explain how it works.(2020)

A delegate is special type of object that contains the details of a method rather than
data.

OR

A delegate is a class type object, which is used to invoke a method that has been encapsulated
into it at the time of its creation.
• A delegate is a reference type variable that holds the references to a method of any class.
• Delegates are especially used for implementing events and the call-back methods.
• All delegates are implicitly derived from the System.Delegate class.

Syntax for delegate declaration is −


delegate <return type> <delegate-name> <parameter list>

1. Declaring a Delegate

• A delegate is declared using the delegate keyword.


• The delegate’s signature (return type and parameters) must match the method it will
reference.

Syntax:

public delegate void Compute(int x, int y);

In the above example:

• public is the access modifier.


• delegate is the keyword.
• void is the return type.
• Compute is the delegate name.
• (int x, int y) is the parameter list.

2. Defining Delegate Methods

• The methods associated with the delegate must have the same signature as the
delegate.

Example of Delegate Methods:

public class Operations


{
// Static method
public static void Add(int x, int y)
{
Console.WriteLine($"Sum = {x + y}");
}

// Instance method
public void Subtract(int x, int y)
{
Console.WriteLine($"Difference = {x - y}");
}
}

Here:

• Add is a static method.


• Subtract is an instance method.

3. Creating Delegate Objects

• Instantiate the delegate and associate it with a method.

Example:

// Delegate for static method


Compute cmp1 = new Compute(Operations.Add);

// Delegate for instance method


Operations op = new Operations();
Compute cmp2 = new Compute(op.Subtract);

4. Invoking Delegate Objects

• Invoke the delegate like a method by passing the required parameters.

Example:

cmp1(10, 5); // Output: Sum = 15


cmp2(10, 5); // Output: Difference = 5

Example of Multicast Delegate and How It Works

Multicast delegates can reference multiple methods. When the delegate is invoked, all
referenced methods are executed in the order they were added.

Example Program:

using System;

namespace DelegateExample
{
// Declare a delegate
public delegate void SampleDelegate(int a, int b);

class MCDelegates
{
// Method 1
public void Add(int n1, int n2)
{
Console.WriteLine($"{n1} + {n2} = {n1 + n2}");
}

// Method 2
public void Subtract(int n1, int n2)
{
Console.WriteLine($"{n1} - {n2} = {n1 - n2}");
}

// Method 3
public void Multiply(int n1, int n2)
{
Console.WriteLine($"{n1} * {n2} = {n1 * n2}");
}

static void Main()


{
MCDelegates obj = new MCDelegates();

// Create a multicast delegate


SampleDelegate del = new SampleDelegate(obj.Add);
del += obj.Subtract; // Add another method
del += obj.Multiply; // Add another method

// Invoke the multicast delegate


Console.WriteLine("Invoking Multicast Delegate:");
del(10, 5);

// Remove a method from the delegate


del -= obj.Subtract;

// Invoke after removal


Console.WriteLine("\nAfter Removing Subtract Method:");
del(10, 5);

Console.ReadKey();
}
}
}

Output:

Invoking Multicast Delegate:


10 + 5 = 15
10 - 5 = 5
10 * 5 = 50

After Removing Subtract Method:


10 + 5 = 15
10 * 5 = 50
How Multicast Delegates Work:

1. Method Addition:
o Methods are added using the += operator.
o del += obj.Subtract; adds Subtract to the delegate.
2. Invocation Order:
o When del(10, 5); is called, the methods are executed sequentially in the
order they were added:
1. Add → Output: 10 + 5 = 15
2. Subtract → Output: 10 - 5 = 5
3. Multiply → Output: 10 * 5 = 50
3. Method Removal:
o The -= operator removes a method from the delegate.
o del -= obj.Subtract; removes the Subtract method from the invocation
list.
4. Final Invocation:
o After removal, only Add and Multiply are executed when del(10, 5); is
called again.

Key Points of Multicast Delegates:

• Can hold multiple methods.


• Execute methods in the order of addition.
• Only works if the return type is void and parameters do not use the out keyword.
• If any method throws an exception, the remaining methods are not executed.

b) Explain exception handling in C#. Give C# code for handling


multiple exceptions. (try catch)(2020)

Exception Handling in C#

Introduction:
Exception handling in C# is a mechanism to handle runtime errors like division by zero or
invalid data type conversion. It prevents program crashes by allowing graceful error recovery.

C# Exception Handling Keywords:


C# uses four main keywords for exception handling:
1. try:
o Defines a block where exceptions may occur.
o Example:

try {
int result = 10 / 0; // Causes DivideByZeroException
}

2. catch:
o Catches exceptions thrown from the try block and handles them.
o Example:

catch (DivideByZeroException ex) {


Console.WriteLine("Error: " + ex.Message);
}

3. finally:
o Executes after try/catch, regardless of exception occurrence. Used for cleanup
tasks.
o Example:

finally {
Console.WriteLine("Execution completed.");
}

4. throw:
o Used to explicitly raise an exception.
o Example:

throw new Exception("Custom error message");

Example Code:

using System;
class Program {
static void Main() {
try {
int number = int.Parse("abc"); // Causes FormatException
}
catch (FormatException ex) {
Console.WriteLine("Exception occurred: " + ex.Message);
}
finally {
Console.WriteLine("Execution completed.");
}
}
}

Custom Exceptions:
You can create user-defined exceptions by inheriting the ApplicationException or
Exception class.
Example:
public class MyException : Exception {
public MyException(string message) : base(message) { }
}

System.Exception Properties:
Important properties of the System.Exception class include:

1. Message: Describes the error.


2. StackTrace: Shows where the error occurred.
3. InnerException: Provides details of the original exception.
4. Source: Identifies the assembly that caused the exception.

Example of Multiple Exception Handling in C#

Here's a C# program demonstrating how to handle multiple exceptions.

using System;

class Program
{
static void Main()
{
try
{
Console.WriteLine("Enter a number:");
int num1 = Convert.ToInt32(Console.ReadLine());

Console.WriteLine("Enter another number:");


int num2 = Convert.ToInt32(Console.ReadLine());

// Potential divide-by-zero exception


int result = num1 / num2;
Console.WriteLine($"Result: {result}");

// Array access exception


int[] numbers = { 1, 2, 3 };
Console.WriteLine($"Fourth element: {numbers[3]}");
}
catch (FormatException ex)
{
Console.WriteLine($"Format Exception: {ex.Message}");
}
catch (DivideByZeroException ex)
{
Console.WriteLine($"Divide by Zero Exception: {ex.Message}");
}
catch (IndexOutOfRangeException ex)
{
Console.WriteLine($"Index Out of Range Exception:
{ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"General Exception: {ex.Message}");
}
finally
{
Console.WriteLine("Execution completed. Cleaning up
resources.");
}
}
}

Explanation of the Example:

1. FormatException:
o Thrown if the user enters non-numeric input when converting with
Convert.ToInt32().
2. DivideByZeroException:
o Thrown if the user enters 0 for num2 during division.
3. IndexOutOfRangeException:
o Thrown when trying to access an array element beyond its bounds.
4. General Exception:
o Catches any other exceptions not handled by specific catch blocks.
5. finally block:
o Executes regardless of whether an exception occurs.

Explain with code example how to implement Custom Exceptions in


C#.
Custom exceptions in C# are user-defined exception classes that inherit from
the built-in Exception class. They are used to represent specific error
conditions that are not covered by standard exceptions, making it easier to
identify, handle, and debug application-specific issues.

Example: Custom Exception in C#

Here’s an example demonstrating a custom exception for invalid age input.

using System;

namespace CustomExceptionExample
{
// 1. Define a custom exception by inheriting from Exception
public class InvalidAgeException : Exception
{
// Default constructor
public InvalidAgeException() : base("Invalid age entered.") { }

// Constructor with custom message


public InvalidAgeException(string message) : base(message) { }

// Constructor with message and inner exception


public InvalidAgeException(string message, Exception
innerException)
: base(message, innerException) { }
}

class Program
{
static void Main()
{
try
{
Console.Write("Enter your age: ");
int age = Convert.ToInt32(Console.ReadLine());

// Throwing custom exception if age is invalid


if (age < 0 || age > 120)
{
throw new InvalidAgeException($"Age '{age}' is not
valid. Age must be between 0 and 120.");
}

Console.WriteLine($"Age entered: {age}");


}
catch (InvalidAgeException ex)
{
Console.WriteLine($"Custom Exception Caught:
{ex.Message}");
}
catch (FormatException ex)
{
Console.WriteLine($"Format Exception: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"General Exception: {ex.Message}");
}
finally
{
Console.WriteLine("Execution completed.");
}
}
}
}

Explanation:

1. Custom Exception Class:


o InvalidAgeException inherits from Exception and provides constructors
for customization.
2. Exception Throwing:
o If the age is outside the valid range (0 to 120), the program throws an
InvalidAgeException.
3. Catch Block:
o The catch block catches and handles the custom exception separately.
Output 1 (Valid Age):
Enter your age: 25
Age entered: 25
Execution completed.

Output 2 (Invalid Age):


Enter your age: -5
Custom Exception Caught: Age '-5' is not valid. Age must be between 0 and
120.
Execution completed.

Output 3 (Invalid Format):


Enter your age: abc
Format Exception: Input string was not in a correct format.
Execution completed.

c) Explain event handling in C# with code example.

d) Explain ADO.NET data providers. (architecture)

e) Explain the architecture of ADO.NET with neat diagram.

Detailed Explanation of ADO.NET Architecture

ADO.NET (ActiveX Data Objects for .NET) is a data access technology in the .NET
framework that provides a set of classes for interacting with data sources, such as relational
databases. It works in both connected and disconnected environments, ensuring efficient data
retrieval and manipulation.

1. .NET Framework Data Provider (Connected Architecture)

The Data Provider facilitates communication between the application and the database. It
consists of the following objects:

A data provider is a set of related components that work together to provide


data in an efficient manner. It is used in ADO.NET for connecting to a database,
executing commands, and retrieving results. The results are either processed
directly or manipulated between tiers and displayed after combining with
multiple sources. The data provider increase performance without functionality.
• Connection Object:
o Establishes and manages the connection to a data source.
o Example: SqlConnection for SQL Server.
o Supports transactions to maintain data integrity.
o Example:

SqlConnection conn = new


SqlConnection("your_connection_string");
conn.Open();

• Command Object:
o Executes SQL queries or stored procedures.
o Can perform CRUD operations (Create, Read, Update, Delete).
o Supports parameters to avoid SQL injection.
o Example:

SqlCommand cmd = new SqlCommand("SELECT * FROM Students",


conn);
SqlDataReader reader = cmd.ExecuteReader();

• DataReader Object:
o Provides a forward-only, read-only stream of data from the database.
o Efficient for retrieving large datasets.
o Example:

while (reader.Read())
{
Console.WriteLine(reader["StudentName"]);
}

• DataAdapter Object:
o Acts as a bridge between the database and the DataSet.
o Fills the DataSet with data and updates the database with changes made in the
DataSet.
o Example:

SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM


Students", conn);
DataSet ds = new DataSet();
adapter.Fill(ds, "Students");

2. DataSet (Disconnected Architecture)

DataSet is a very useful in-memory representation of data and acts as the core of a wide
variety of the data based applications. A DataSet can be considered as a local copy of the
relevant portions of the database. The data in the DataSet can be manipulated and updated
independent of the database. You can load the data in the DataSet from any valid source, such
as the MicrosoftSQLServer database, Oracle Database, or Microsoft Access database.

The DataSet represents an in-memory cache of data that can work independently of the
database. It allows manipulation of data without an active connection.
• DataTableCollection:
o Contains one or more DataTable objects, representing database tables.
o Example: ds.Tables["Students"]
• DataTable Object:
o Represents a table with rows and columns.
o Example:

DataTable dt = ds.Tables["Students"];
foreach (DataRow row in dt.Rows)
{
Console.WriteLine(row["StudentName"]);
}

• DataRowCollection:
o Represents individual rows of data.
o Supports adding, editing, and deleting rows.
• DataColumnCollection:
o Represents the structure of the table with columns.
o Example: dt.Columns["StudentName"]
• ConstraintCollection:
o Defines rules like primary keys and foreign keys.
o Ensures data integrity within the DataSet.
• DataRelationCollection:
o Manages relationships between tables.
o Example: Parent-child relationships between Orders and OrderDetails
tables.

3. Data Flow in ADO.NET Architecture

1. The application sends a request to access or manipulate data.


2. The Connection object connects to the database.
3. The Command object executes the query.
4. The DataReader reads data if real-time access is needed, or the DataAdapter fills
the DataSet for disconnected access.
5. The DataSet stores data in memory, where changes can be made.
6. The DataAdapter updates the database with modified data.
7. The Connection object closes the connection after completion.

4. XML Integration in ADO.NET

ADO.NET supports XML for data exchange and storage:

• Read/Write XML: DataSet can read from and write to XML files.
• Schema Definition: XML schema defines the structure of the DataSet.
• Example:

ds.WriteXml("Students.xml"); // Export to XML


ds.ReadXml("Students.xml"); // Import from XML

5. Key Features of ADO.NET Architecture

• Connected & Disconnected Access: Supports both real-time and offline data
manipulation.
• Efficient Data Retrieval: DataReader for fast, forward-only access.
• Data Integrity: Supports transactions and constraints.
• XML Support: Easy data exchange with XML integration.
• Cross-Database Compatibility: Works with SQL Server, Oracle, MySQL, and
others.

f) Explain the following with example:


i) Retrieving Data Using an ADO.NET DataReader object
ii) Populating a DataSet from a DataAdapter

g) Explain the procedure of getting connected to a SQL Serverdatabase and running the
following queries.
i) insert a record into a table
ii) delete records from the table
iii) executing a SELECT query
(connection object, getting connected to db) (2020)
Module 4

1. Explain different types of KeyBoard events. Demonstrate with


example. (2020)

In Windows Forms, keyboard events are triggered when a user presses or releases a key.
These events can be handled in any control that inherits from
System.Windows.Forms.Control.

There are three main keyboard events:

1. KeyDown: Triggered when a key is initially pressed.


2. KeyPress: Triggered when a key is pressed and released (only for printable
characters).
3. KeyUp: Triggered when a key is released.

Detailed Explanation of Keyboard Events

1. KeyDown Event

• This event occurs when a key is first pressed.


• It is often used to detect non-printable keys like Ctrl, Alt, Shift, or function keys.
• The event handler receives KeyEventArgs, which contains information like KeyCode
and Modifiers.
2. KeyPress Event

• Occurs after KeyDown and before KeyUp but only for printable characters.
• The event handler receives KeyPressEventArgs, which provides the ASCII character
of the key pressed (KeyChar).
• Cannot detect non-character keys like F1, Enter, Backspace.

3. KeyUp Event

• This event occurs when a key is released.


• It is useful for detecting when the user has finished pressing a key.
• Like KeyDown, it provides KeyEventArgs to determine which key was released.

Example Code: Keyboard Event Handling in Windows Forms


using System;
using System.Windows.Forms;

namespace KeyPressExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

// Handle the KeyPress event for the form


private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
// Check if the user pressed the 'A' key
if (e.KeyChar == 'a')
{
MessageBox.Show("You pressed the 'A' key!");
}
}

// Handle the KeyDown event


private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
MessageBox.Show("Escape key was pressed!");
}
}

// Handle the KeyUp event


private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
MessageBox.Show("Enter key released!");
}
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// Subscribe to the keyboard events
this.KeyPress += new KeyPressEventHandler(Form1_KeyPress);
this.KeyDown += new KeyEventHandler(Form1_KeyDown);
this.KeyUp += new KeyEventHandler(Form1_KeyUp);
}
}
}

How the Example Works

1. KeyPress Event:
o If the user presses the A key, a message box displays "You pressed the 'A'
key!".
o Works only for printable characters.
2. KeyDown Event:
o If the user presses the Escape key, a message box displays "Escape key was
pressed!".
o Works for all keys, including function and control keys.
3. KeyUp Event:
o If the user releases the Enter key, a message box displays "Enter key
released!".
o Useful for detecting key release actions.

Summary Table

Supports All
Event Triggered When Key Information
Keys?
KeyDown When a key is first pressed Yes KeyCode, Modifiers

When a key is pressed & released No (only KeyChar (ASCII


KeyPress
(printable only) printable) character)
KeyUp When a key is released Yes KeyCode, Modifiers
2. Illustrate working with following controls with a Windows Forms
Application example: (2020)
a. CheckBox
b. RadioButton
c. GroupBox

Windows Forms applications provide UI controls such as CheckBoxes, RadioButtons, and


GroupBoxes, which help users interact with forms efficiently. Below is a detailed
explanation along with a C# example demonstrating how these controls work.

1. CheckBox Control
A CheckBox is a small square that can be either checked (true) or unchecked (false). It
allows users to select multiple options at once.

• A CheckBox is a small square that either is blank or contains a check mark.

• When the user clicks a CheckBox to select it, a check mark appears in the box.

• If the user clicks the CheckBox again to deselect it, the check mark is removed.

• You can also configure a CheckBox to toggle between three states (checked, unchecked,
and indeterminate) by setting its ThreeState property to true.

• Any number of CheckBoxes can be selected at a time.

• CheckBox allows a website visitor to select (checked) a true or false condition.

• The CheckBox control creates a checkbox on a web forms page that allows users to switch
between a true or false state.

• CheckBox Text property creates a caption for it.

• The TextAlign property allows left or right alignment of the caption.

• To determine whether a CheckBox is checked (selected), test the Checked property.

• AutoPostBack property value true enables automatic posting to the server.


• CheckedChanged event is raised when the CheckBox state changes (true or false).

2. RadioButton Control
A RadioButton is used when selecting one option from a group of choices. When a
RadioButton is selected, other buttons in the group are automatically deselected.

Common Properties of RadioButton:

• Checked: Indicates if the RadioButton is selected (true or false).


• Text: Displays text next to the RadioButton.

Common Events of RadioButton:

• CheckedChanged: Triggered when the RadioButton’s state changes.

Radio buttons (defined with class RadioButton) are similar to CheckBoxes in that they also have two
states—selected and not selected (also called deselected). However, RadioButtons normally appear
as a group, in which only one RadioButton can be selected at a time.

✓ Selecting one RadioButton in the group forces all the others to be deselected. Therefore,
RadioButtons are used to represent a set of mutually exclusive options (i.e., a set in which multiple
options cannot be selected at the same time).
3. GroupBox Control
A GroupBox is used to organize related controls (e.g., multiple RadioButtons) into a single
unit with a visible caption.

• Moving the GroupBox moves all the controls inside it.


• GroupBoxes do not support scrollbars.

Common Properties of GroupBox:

• Text: Specifies the title (caption) of the GroupBox.


• Controls: Holds the collection of controls within the GroupBox.
3. Explain different types of mouse events and mouse event
handling.

In C#, mouse events are triggered based on user interaction with a control (like buttons, text
boxes, etc.) using the mouse. These events are classified into different types and provide the
ability to react to specific mouse actions. Below are the different types of mouse events and
how they can be handled in C#:

Types of Mouse Events


1. MouseDown: Triggered when the mouse button is pressed while the mouse pointer is
over a control.
2. MouseEnter: Occurs when the mouse pointer enters the control's area.
3. MouseHover: Occurs when the mouse pointer is moved over the control, hovering
for a while.
4. MouseLeave: Occurs when the mouse pointer leaves the control's area.
5. MouseMove: Triggered when the mouse pointer is moved while over a control.
6. MouseUp: Occurs when the mouse button is released while the mouse pointer is over
a control.
7. MouseWheel: Occurs when the mouse wheel is rotated while the control is focused.

Mouse Event Handling in C#

Mouse events can be handled for any control that derives from the
System.Windows.Forms.Control class. Each event handler receives a MouseEventArgs
object, which contains information like the coordinates of the mouse pointer, the button
pressed, and the number of times the mouse was clicked.

MouseEventArgs Class

The MouseEventArgs class contains properties like:

• Button: Indicates which mouse button was pressed (Left, Right, or Middle).
• Clicks: The number of times the mouse button was clicked.
• X: The X-coordinate where the event occurred.
• Y: The Y-coordinate where the event occurred.

Example of Mouse Event Handling

In this example, we handle the MouseEnter and MouseLeave events to change the
background and foreground colors of the text boxes when the mouse pointer enters or leaves
the area of the text boxes.

csharp
CopyEdit
using System;
using System.Windows.Forms;
using System.Drawing;

namespace MouseEventExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void textBox1_MouseEnter(object sender, EventArgs e)


{
// Change background and text color when mouse enters
textBox1.BackColor = Color.Green;
textBox1.ForeColor = Color.White;
}

private void textBox1_MouseLeave(object sender, EventArgs e)


{
// Change background and text color when mouse leaves
textBox1.BackColor = Color.White;
textBox1.ForeColor = Color.Black;
}

private void textBox2_MouseEnter(object sender, EventArgs e)


{
// Change background and text color when mouse enters
textBox2.BackColor = Color.Blue;
textBox2.ForeColor = Color.White;
}

private void textBox2_MouseLeave(object sender, EventArgs e)


{
// Change background and text color when mouse leaves
textBox2.BackColor = Color.White;
textBox2.ForeColor = Color.Black;
}

private void button1_Click(object sender, EventArgs e)


{
// Show message with values entered in textboxes
MessageBox.Show("Your name is " + textBox1.Text + " " +
textBox2.Text);
}
}
}

Explanation of Code

1. MouseEnter Event: Changes the background color of the textBox1 to Green and
textBox2 to Blue when the mouse enters the control.
2. MouseLeave Event: Reverts the background color back to White and the text color
to Black when the mouse leaves the control.

By using these events, you can enhance user experience by providing visual feedback based
on mouse movements.

Summary

• Mouse events are a key feature in event-driven programming in C#.


• You can use mouse events like MouseDown, MouseEnter, MouseMove, and MouseUp to
handle different types of mouse interactions with controls.
• Using MouseEventArgs, you can access useful information like the mouse position
and which button was pressed, enabling dynamic control of application behavior
based on user interactions.
4. Explain WPF architecture with a neat diagram.

WPF (Windows Presentation Foundation) Architecture – Detailed


Explanation

WPF architecture is designed to provide a rich UI framework by leveraging hardware


acceleration via Direct3D. It consists of three main layers:

1. Managed WPF Layer


2. Unmanaged or Media Integration Layer
3. Core Operating System Layer

Each of these layers plays a crucial role in rendering UI, processing user input, and
interacting with the hardware.

1. Managed WPF Layer (High-Level API)


This is the topmost layer, written in managed code (C# and .NET), which interacts with the
lower layers. It consists of three main assemblies:
1.1 WindowsBase.dll

• Contains core infrastructure classes used in every WPF application.


• Provides services like threading, security, dependency properties, and input
events.
• Includes base classes for 2D graphics, animation, and data binding.

1.2 PresentationFramework.dll

• Provides the high-level WPF components used in applications.


• Contains Windows, Controls, Styles, Layout Panels, and Templates.
• Any UI element that developers interact with (like Button, ListBox, Grid) is defined
here.
• It relies on PresentationCore.dll for rendering.

1.3 PresentationCore.dll

• Defines low-level UI building blocks such as UIElement, Visual, and


DrawingContext.
• These types serve as the foundation for all controls and elements in WPF.
• Provides drawing primitives (lines, shapes, text) used by PresentationFramework.
• Allows custom controls and advanced rendering through Visual objects.

2. Unmanaged Media Integration Layer


This layer is written in unmanaged code (C++) to optimize performance and interacts with
Direct3D for rendering.

2.1 MilCore.dll (Media Integration Library Core)

• Heart of WPF Rendering Engine – responsible for drawing UI elements on the


screen.
• Converts high-level XAML elements into Direct3D commands for GPU rendering.
• It is written in unmanaged code for speed and efficiency.
• Handles compositing, transformations, animations, and transparency effects.
• Used by Windows Vista and Windows 7 for rendering desktops (DWM –
Desktop Window Manager).

2.2 WindowsCodecs.dll

• Responsible for image processing and bitmap decoding.


• Provides support for various image formats (JPEG, PNG, BMP, TIFF, GIF).
• Handles image scaling, color correction, and transformations.
• Works with Direct3D to render images efficiently.
3. Core Operating System Layer
This layer interacts with the underlying Windows OS components and hardware.

3.1 Direct3D

• DirectX component used to render 2D and 3D graphics in WPF.


• Uses hardware acceleration via GPU for smooth animations and high-performance
graphics.
• Converts UI elements into renderable textures for better performance.
• WPF uses vector-based rendering, making UI resolution-independent.

3.2 User32.dll

• Responsible for handling user interactions, such as mouse clicks, keyboard input,
and window management.
• Works with WPF for event-driven programming.

3.3 GDI (Graphics Device Interface)

• Traditional Windows rendering engine (used in WinForms and older applications).


• WPF bypasses GDI and directly interacts with Direct3D for rendering.
• However, GDI is still used for legacy operations and text rendering in some
scenarios.

3.4 Device Driver

• Lowest layer responsible for interacting with the hardware (GPU, Monitor, Input
devices).
• Direct3D sends rendering commands to the device driver, which draws the final
image on the screen.
• Allows hardware acceleration for smooth UI performance.

How WPF Works Step-by-Step


1. WPF Application Code (XAML & C#) interacts with
PresentationFramework.dll (UI controls, layouts).
2. PresentationFramework calls PresentationCore.dll, which uses base types
(UIElement, Visual) for rendering.
3. PresentationCore sends the rendering commands to MilCore.dll (Media
Integration Layer).
4. MilCore translates UI elements into Direct3D-compatible graphics.
5. Direct3D renders the elements on the GPU, bypassing GDI.
6. Final image is displayed on the screen using the Device Driver.
Key Advantages of WPF Architecture
• Hardware-Accelerated Rendering: Uses Direct3D and GPU instead of GDI for
better performance.
• Resolution Independence: Uses vector-based graphics, so UI elements scale
smoothly.
• Separation of Concerns: Managed and unmanaged layers ensure better
performance and maintainability.
• Better Media & Animation Support: MilCore enables high-performance
animations and effects.

5. Discuss the properties, events of CheckedListBox control and demonstrate how to


use a CheckedListBox, add items,check/ uncheck items programmatically, and handle
item check events.

heckedListBox Control in C#
The CheckedListBox control in C# is a specialized version of the ListBox control. It allows
users to select multiple items with checkboxes. This is particularly useful when you want to
display a list of options that can be selected or deselected independently.

Properties of CheckedListBox

1. CheckOnClick:
o Type: bool
o Description: Gets or sets a value indicating whether the check box should be
toggled when an item is selected. If true, selecting an item will automatically
check or uncheck the item.
o Example: checkedListBox.CheckOnClick = true;
2. ColumnWidth:
o Type: int
o Description: Gets or sets the width of columns in a multicolumn
CheckedListBox. This property is only applicable if the MultiColumn
property is set to true.
o Example: checkedListBox.ColumnWidth = 100;
3. Items:
o Type: CheckedListBox.ObjectCollection
o Description: Gets the collection of items in the CheckedListBox. This
collection allows you to add, remove, and manipulate items in the list.
o Example: checkedListBox.Items.Add("Item 1");
4. MultiColumn:
o Type: bool
o Description: Gets or sets a value indicating whether the CheckedListBox
supports multiple columns. When set to true, the list box will display items in
multiple columns.
o Example: checkedListBox.MultiColumn = true;
5. ScrollAlwaysVisible:
o Type: bool
o Description: Gets or sets a value indicating whether the vertical scrollbar is
always shown, even if the number of items does not require scrolling.
o Example: checkedListBox.ScrollAlwaysVisible = true;
6. SelectedIndex:
o Type: int
o Description: Gets or sets the zero-based index of the currently selected item in
the CheckedListBox. If no item is selected, it returns -1.
o Example: int selectedIndex = checkedListBox.SelectedIndex;
7. SelectedItem:
o Type: object
o Description: Gets or sets the currently selected item in the CheckedListBox.
o Example: object selectedItem = checkedListBox.SelectedItem;

Events of CheckedListBox

1. SelectedIndexChanged:
o Occurs when the SelectedIndex property or the SelectedIndices collection
has changed (i.e., the selection has changed).
o Example:

csharp
CopyEdit
private void CheckedListBox1_SelectedIndexChanged(object sender,
EventArgs e)
{
lblColor.Text = checkedListBox1.SelectedItem.ToString();
}

2. ItemCheck:
o Occurs when an item in the CheckedListBox is checked or unchecked. This
event is triggered before the item's state changes.
o Example:

csharp
CopyEdit
private void checkedListBox1_ItemCheck(object sender,
ItemCheckEventArgs e)
{
MessageBox.Show($"Item {e.Index} will be checked: {e.NewValue}");
}

Demonstrating the Usage of CheckedListBox

Steps to Add Items to the CheckedListBox:

1. Add Items to CheckedListBox:


o You can add items to the CheckedListBox using the Items.Add method.

csharp
CopyEdit
checkedListBox1.Items.Add("Item 1");
checkedListBox1.Items.Add("Item 2");
checkedListBox1.Items.Add("Item 3");

2. Set the CheckOnClick Property:


o By setting CheckOnClick to true, the item will automatically be checked or
unchecked when clicked.

csharp
CopyEdit
checkedListBox1.CheckOnClick = true;

3. Handle Item Check Events:


o You can handle the ItemCheck event to detect when an item’s check state
changes. This is useful for custom logic when an item is checked or
unchecked.

csharp
CopyEdit
private void checkedListBox1_ItemCheck(object sender,
ItemCheckEventArgs e)
{
MessageBox.Show($"Item {e.Index} will be checked: {e.NewValue}");
}

Programmatically Checking/Unchecking Items:

You can check or uncheck items programmatically by manipulating the SetItemChecked


method or by using the CheckedItems collection.

• Check an Item:

csharp
CopyEdit
checkedListBox1.SetItemChecked(0, true); // Checks the item at index
0

• Uncheck an Item:

csharp
CopyEdit
checkedListBox1.SetItemChecked(0, false); // Unchecks the item at
index 0

• Check Multiple Items:

csharp
CopyEdit
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
checkedListBox1.SetItemChecked(i, true); // Checks all items
}

Complete Example:

csharp
CopyEdit
using System;
using System.Windows.Forms;

namespace CheckedListBoxExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
// Adding items to CheckedListBox
checkedListBox1.Items.Add("Item 1");
checkedListBox1.Items.Add("Item 2");
checkedListBox1.Items.Add("Item 3");

// Set CheckOnClick to true


checkedListBox1.CheckOnClick = true;

// Handle ItemCheck event


checkedListBox1.ItemCheck += new
ItemCheckEventHandler(checkedListBox1_ItemCheck);
}

private void checkedListBox1_ItemCheck(object sender,


ItemCheckEventArgs e)
{
// Handle the item check event
MessageBox.Show($"Item {e.Index} will be checked:
{e.NewValue}");
}

private void buttonCheckAll_Click(object sender, EventArgs e)


{
// Check all items programmatically
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
checkedListBox1.SetItemChecked(i, true);
}
}

private void buttonUncheckAll_Click(object sender, EventArgs e)


{
// Uncheck all items programmatically
for (int i = 0; i < checkedListBox1.Items.Count; i++)
{
checkedListBox1.SetItemChecked(i, false);
}
}
}
}

Explanation of the Code:

• Form1_Load: This event is triggered when the form is loaded. It adds items to the
CheckedListBox and sets the CheckOnClick property to true so that clicking an
item toggles its checked state.
• ItemCheck Event: When the user checks or unchecks an item, the ItemCheck event
is triggered, and a message box shows the item index and its new state.
• Check/Uncheck Buttons: There are buttons to check or uncheck all items
programmatically using the SetItemChecked method.
6. Explain the Control class properties and methods.

Control Class Properties and Methods

The Control class in Windows Forms serves as the base class for many controls like Button,
TextBox, Label, etc. It provides fundamental properties, methods, and events that help
control the behavior and appearance of the UI components. Below is an explanation of some
important properties and methods of the Control class.

Properties of the Control Class

1. Anchor:
o Type: AnchorStyles
o Description: Defines how a control is resized relative to its container when
the container is resized. It allows you to set which edges of the control are
"anchored" to the container.
o Example: Setting Anchor to Top | Left means the control will stay at the
top-left corner when the form is resized.
2. BackColor:
o Type: Color
o Description: Gets or sets the background color of the control.
o Example: control.BackColor = Color.Red;
3. Bottom:
o Type: int
o Description: Gets or sets the distance between the top of the parent container
and the bottom of the control. It is not the height, but the vertical position.
o Example: control.Bottom = 200;
4. ClientSize:
o Type: Size
o Description: Gets or sets the height and width of the client area of the control
(i.e., the area excluding borders, scroll bars, etc.).
o Example: control.ClientSize = new Size(200, 100);
5. Dock:
o Type: DockStyle
o Description: Gets or sets how the control is docked to its parent container. It
can be docked to the top, bottom, left, right, or fill the entire container.
o Example: control.Dock = DockStyle.Fill;
6. Enabled:
o Type: bool
o Description: Gets or sets whether the control is enabled and can receive user
input. When set to false, the control is disabled and cannot interact with the
user.
o Example: control.Enabled = false;
7. ForeColor:
o Type: Color
o Description: Gets or sets the foreground color (text color) of the control.
o Example: control.ForeColor = Color.Blue;
8. Height:
o Type: int
o Description: Gets or sets the height of the control.
o Example: control.Height = 50;
9. Left:
o Type: int
o Description: Gets or sets the distance between the left edge of the control and
the left edge of its parent container.
o Example: control.Left = 100;
10. Name:
o Type: string
o Description: Gets or sets the name of the control. The name is used to
reference the control programmatically.
o Example: control.Name = "myTextBox";
11. Parent:
o Type: Control
o Description: Gets or sets the parent container of the control. This is the form
or container that holds the control.
o Example: control.Parent = this;
12. TabIndex:
o Type: int
o Description: Gets or sets the index of the control in the tab order for its
container.
o Example: control.TabIndex = 1;
13. TabStop:
o Type: bool
o Description: Gets or sets whether the control can be selected by pressing the
Tab key.
o Example: control.TabStop = true;
14. Tag:
o Type: object
o Description: A user-defined property for storing arbitrary data or metadata
about the control.
o Example: control.Tag = "Some data";
15. Top:
o Type: int
o Description: Gets or sets the distance between the top of the control and the
top of its container.
o Example: control.Top = 100;
16. Visible:
o Type: bool
o Description: Gets or sets whether the control is visible at runtime.
o Example: control.Visible = true;
17. Width:
o Type: int
o Description: Gets or sets the width of the control.
o Example: control.Width = 200;

Methods of the Control Class

1. BringToFront:
o Description: Brings the control to the front of the z-order, making it appear
above other controls in its parent container.
o Example: control.BringToFront();
2. CenterToParent:
o Description: Centers the control within its parent container.
o Example: control.CenterToParent();
3. Click:
o Description: The Click method is called when the user clicks the control (for
controls like buttons, etc.).
o Example: You can attach an event handler for the Click event in the form
designer or code.
4. Focus:
o Description: Sets the focus to the control, making it the active control.
o Example: control.Focus();
5. Hide:
o Description: Hides the control by setting its Visible property to false.
o Example: control.Hide();
6. Invalidate:
o Description: Forces the control to redraw itself. This is useful for refreshing
the control when its appearance needs to be updated.
o Example: control.Invalidate();
7. PerformLayout:
o Description: Forces the control to re-layout itself, which is useful when the
size or position of the control has changed dynamically.
o Example: control.PerformLayout();
8. Refresh:
o Description: Forces the control to redraw itself immediately.
o Example: control.Refresh();
9. ResetBackColor:
o Description: Resets the BackColor property to its default value.
o Example: control.ResetBackColor();
10. ResetForeColor:
o Description: Resets the ForeColor property to its default value.
o Example: control.ResetForeColor();
11. Show:
o Description: Makes the control visible if it is hidden.
o Example: control.Show();
12. Update:
o Description: Forces the control to redraw itself if necessary. It is used to
update the control's visual appearance.
o Example: control.Update();

Conclusion

The Control class serves as the foundation for most user interface components in Windows
Forms applications. Its properties allow for customization of appearance, behavior, layout,
and interactivity of controls, while its methods provide functionality for managing the
control's visibility, layout, and interaction with other components.

By using these properties and methods effectively, you can create responsive and dynamic
user interfaces in your Windows Forms applications.

7. Using Windows Forms, describe the steps to:


i) Create a simple event-driven GUI.
ii) Implement a DateTimePicker control.

Windows Forms provides a graphical user interface (GUI) framework for creating event-
driven applications in .NET using C#. Below, we will discuss the steps to:

1. Create a simple event-driven GUI


2. Implement a DateTimePicker control

(i) Creating a Simple Event-Driven GUI in Windows Forms


An event-driven GUI responds to user interactions, such as button clicks, key presses, and
mouse movements. Below are the steps to create a basic event-driven Windows Forms
application in C#.

Steps to Create a Simple Event-Driven GUI

Step 1: Create a Windows Forms Application

1. Open Visual Studio.


2. Click Create a new project.
3. Select Windows Forms App (.NET Framework) and click Next.
4. Enter the project name and location, then click Create.

Step 2: Design the Form

1. From the Toolbox, drag and drop a Button control onto the Form.
2. Set the button’s properties in the Properties Window:
o Text → "Click Me"
o Name → btnClickMe
3. Drag a Label control onto the Form.
o Text → "Hello, World!" (or leave it blank)
o Name → lblMessage

Step 3: Add an Event Handler for the Button Click Event

1. Double-click the Button to generate a Click event handler.


2. Inside the button_Click method, add code to change the label text.

Step 4: Write Code for the Event Handler

Modify the generated method in the Form1.cs file as follows:

csharp
CopyEdit
using System;
using System.Windows.Forms;

namespace EventDrivenGUI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btnClickMe_Click(object sender, EventArgs e)


{
lblMessage.Text = "Button was Clicked!";
}
}
}
Step 5: Run the Application

1. Press F5 or click Start in Visual Studio.


2. Click the "Click Me" button, and the label text should change.

(ii) Implementing a DateTimePicker Control in Windows


Forms
The DateTimePicker control allows users to select dates and times in a formatted manner.

Steps to Add and Use a DateTimePicker Control

Step 1: Add a DateTimePicker Control

1. Open Visual Studio and create a new Windows Forms App (if not already created).
2. Drag a DateTimePicker from the Toolbox onto the Form.
o Name → dtpDateSelector
3. Drag a Label control onto the Form to display the selected date.
o Name → lblSelectedDate
o Text → "Selected Date: "

Step 2: Modify DateTimePicker Properties (Optional)

• Change the format:


o Format → Long (Displays full date)
o Format → Short (Displays MM/DD/YYYY)
o Format → Time (Displays time)
o Format → Custom and set CustomFormat = "MMMM dd, yyyy"
• Set Min and Max Dates:

csharp
CopyEdit
dtpDateSelector.MinDate = new DateTime(2000, 1, 1);
dtpDateSelector.MaxDate = DateTime.Today;

Step 3: Handle the ValueChanged Event

1. Double-click the DateTimePicker control to generate a ValueChanged event.


2. Modify the method in Form1.cs:

csharp
CopyEdit
using System;
using System.Windows.Forms;

namespace DateTimePickerDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void dtpDateSelector_ValueChanged(object sender, EventArgs


e)
{
lblSelectedDate.Text = "Selected Date: " +
dtpDateSelector.Value.ToShortDateString();
}
}
}

Step 4: Run the Application

1. Press F5 to start the application.


2. Select a date from the DateTimePicker, and the label will update to display the
selected date.

Conclusion

• Event-driven GUI applications respond to user actions like button clicks.


• Windows Forms allows the creation of graphical applications using controls like
Button, Label, and DateTimePicker.
• The DateTimePicker control helps users select dates efficiently and supports
formatting options.

This completes the implementation of a simple event-driven GUI and the DateTimePicker
control in Windows Forms.
8. Explain the following:
i) MDI windows (2020)
ii) RadioButton (Refer above)

MDI (Multiple Document Interface) is a type of user interface that allows an application to
contain multiple child windows within a single parent window. This is useful for applications
where users need to open, view, and work with multiple documents at the same time.

In contrast to SDI (Single Document Interface), where only one document is open at a time
(e.g., Notepad), MDI applications (like Microsoft Word in multiple-document mode) allow
multiple documents within a single parent window.

Key Components of MDI Windows

1. MDI Parent Form


o This is the main window that contains all child forms.
o It acts as a container for multiple child forms.
o The IsMdiContainer property must be set to true.
2. MDI Child Forms
o These are the individual document windows inside the parent form.
o Multiple child forms can be opened simultaneously.
o They are created dynamically at runtime.

Steps to Create an MDI Application in Windows Forms

Step 1: Create an MDI Parent Form

1. Open Visual Studio and create a new Windows Forms App.


2. In the Properties Window, set the IsMdiContainer property of the main form
(Form1) to true.
3. Add a MenuStrip to Form1 for managing child windows.

Step 2: Add Menu Items to Create Child Forms

1. Click the MenuStrip, then add a menu item called "File".


2. Under "File", add a submenu called "New".

Step 3: Write Code to Open Child Forms

1. Double-click the "New" menu item to generate a Click event.


2. Write the following code in Form1.cs:

csharp
CopyEdit
using System;
using System.Windows.Forms;

namespace MDIExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void newToolStripMenuItem_Click(object sender, EventArgs e)


{
// Create a new child form
Form childForm = new Form();
childForm.MdiParent = this; // Set the parent form
childForm.Text = "Child Window " + this.MdiChildren.Length;
childForm.Show();
}
}
}

Step 4: Run the Application

1. Press F5 to start the application.


2. Click "File" → "New" to open multiple child windows inside the parent window.

You might also like