C#Mod3and4 1
C#Mod3and4 1
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.
1. Declaring a Delegate
Syntax:
• The methods associated with the delegate must have the same signature as the
delegate.
// Instance method
public void Subtract(int x, int y)
{
Console.WriteLine($"Difference = {x - y}");
}
}
Here:
Example:
Example:
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}");
}
Console.ReadKey();
}
}
}
Output:
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.
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.
try {
int result = 10 / 0; // Causes DivideByZeroException
}
2. catch:
o Catches exceptions thrown from the try block and handles them.
o Example:
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:
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:
using System;
class Program
{
static void Main()
{
try
{
Console.WriteLine("Enter a number:");
int num1 = Convert.ToInt32(Console.ReadLine());
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.
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.") { }
class Program
{
static void Main()
{
try
{
Console.Write("Enter your age: ");
int age = Convert.ToInt32(Console.ReadLine());
Explanation:
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.
The Data Provider facilitates communication between the application and the database. It
consists of the following objects:
• 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:
• 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:
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.
• Read/Write XML: DataSet can read from and write to XML files.
• Schema Definition: XML schema defines the structure of the DataSet.
• Example:
• 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.
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
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.
1. KeyDown 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
namespace KeyPressExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
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
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.
• 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.
• The CheckBox control creates a checkbox on a web forms page that allows users to switch
between a true or false state.
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.
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.
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#:
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
• 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.
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();
}
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
Each of these layers plays a crucial role in rendering UI, processing user input, and
interacting with the hardware.
1.2 PresentationFramework.dll
1.3 PresentationCore.dll
2.2 WindowsCodecs.dll
3.1 Direct3D
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.
• 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.
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}");
}
csharp
CopyEdit
checkedListBox1.Items.Add("Item 1");
checkedListBox1.Items.Add("Item 2");
checkedListBox1.Items.Add("Item 3");
csharp
CopyEdit
checkedListBox1.CheckOnClick = true;
csharp
CopyEdit
private void checkedListBox1_ItemCheck(object sender,
ItemCheckEventArgs e)
{
MessageBox.Show($"Item {e.Index} will be checked: {e.NewValue}");
}
• 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
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();
}
• 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.
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.
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;
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.
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. 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
csharp
CopyEdit
using System;
using System.Windows.Forms;
namespace EventDrivenGUI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
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: "
csharp
CopyEdit
dtpDateSelector.MinDate = new DateTime(2000, 1, 1);
dtpDateSelector.MaxDate = DateTime.Today;
csharp
CopyEdit
using System;
using System.Windows.Forms;
namespace DateTimePickerDemo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Conclusion
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.
csharp
CopyEdit
using System;
using System.Windows.Forms;
namespace MDIExample
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}