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

C# UNIT 3

The document provides an overview of key concepts in C# including interfaces, enumerations, cloning, comparison methods, indexers, delegates, events, and multithreading. It explains how interfaces serve as blueprints for classes, how enums improve code readability, and how delegates facilitate event handling. Additionally, it covers the lifecycle of threads and the properties and methods associated with the Thread class, emphasizing the importance of multithreading in application performance.

Uploaded by

salhamussa2001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

C# UNIT 3

The document provides an overview of key concepts in C# including interfaces, enumerations, cloning, comparison methods, indexers, delegates, events, and multithreading. It explains how interfaces serve as blueprints for classes, how enums improve code readability, and how delegates facilitate event handling. Additionally, it covers the lifecycle of threads and the properties and methods associated with the Thread class, emphasizing the importance of multithreading in application performance.

Uploaded by

salhamussa2001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 69

INTERFACE ANS COLLECTIONS

INTERFACE

 Interface in C# is a blueprint of a class.

 It is like abstract class because all the methods which are declared inside the interface are abstract methods.

 It cannot have method body and cannot be instantiated.

 It is used to achieve multiple inheritance which can't be achieved by class. It is used to achieve fully abstraction because

it cannot have method body.

 Its implementation must be provided by class or struct. The class or struct which implements the interface, must provide

the implementation of all the methods declared inside the interface


using System;
public interface Drawable
{
DECLARING INTERFACES void draw();
}
Interfaces are declared using the interface keyword. public class Rectangle : Drawable
{
It is similar to class declaration. Interface statements are public by default. public void draw()
{
Following is an example of an interface declaration − Console.WriteLine("drawing re
ctangle...");
public interface ITransactions { }
}
// interface members public class TestInterface
{
void showTransaction(); public static void Main()
{
double getAmount(); Drawable d;
d = new Rectangle();
} d.draw();
}
}
ENUMERATION (OR ENUM) OR ENUMERATOR

Enumeration (or enum) is a value data type in C#.

It is mainly used to assign the names or string values to integral constants, that make a program easy to read and maintain.

For example, the 4 suits in a deck of playing cards may be 4 enumerators named Club, Diamond, Heart, and Spade,

belonging to an enumerated type named Suit.

Syntax: in above syntax, Enum_variable is the name of the enumerator,


and string_1 is attached with value 0, string_2 is attached value
enum Enum_variable 1 and so on. Because by default, the first member of an enum
{ has the value 0, and the value of each successive enum member
string_1...; is increased by 1. We can change this default value.
string_2...;
.
.
}
// Main Method
// C# program to illustrate the enums static void Main(string[] args)
// with their default values {
using System;
namespace ConsoleApplication1 { // getting the integer values of data members..
Console.WriteLine("The value of jan in month "
// making an enumerator 'month' +
enum month "enum is " + (int)month.jan);
{ Console.WriteLine("The value of feb in month "
+
// following are the data members "enum is " + (int)month.feb);
jan, Console.WriteLine("The value of mar in month "
feb, +
mar, "enum is " + (int)month.mar);
apr, Console.WriteLine("The value of apr in month "
may +
"enum is " + (int)month.apr);
} Console.WriteLine("The value of may in month
"+
class Program { "enum is " + (int)month.may);
}
}
}
CLONE() METHOD OR CLONABLE OBJECT\

 In C#, Clone() is a String method. It is used to clone the string object, which returns another copy of that data.
C# program to illustrate
In other words, it returns a reference to this instance of String. // Clone() method
using System;
 The return value will be only another view of the same data. class Geeks {

 Clone method called directly on current String instance. // Main Method


public static void Main(string[] args)
Syntax: {
string s1 = "GeeksForgeeks";
public object Clone() // Cannot implicitly convert
// type object to the string.
// So explicit conversion
// using Clone() method
string s2 = (String)s1.Clone();

// Displaying both the string


Console.WriteLine("String : {0}", s1);
Console.WriteLine("Clone String : {0}", s2);
}
}
Compare(Object, Object) Method

Definition
Namespace: System.Collections
Assembly:System.Runtime.dll
 Performs a case-sensitive comparison of two objects of the same type and returns a value indicating whether
one is less than, equal to, or greater than the other.
SYNTAX
public int Compare (object? a, object? b);
Parameters
A Object
The first object to compare.
B Object
The second object to compare.
Returns Int32
A signed integer that indicates the relative values of a and b, as shown in the following table.
VALUE MEANING

Less than zero a is less than b.


Zero a equals b.
Greater than zero a is greater than b.

Implements
Compare(Object, Object)
Exceptions
ArgumentException
Neither a nor b implements the IComparable interface.
-or-
a and b are of different types and neither one can handle
comparisons with the other.
Indexers
 An indexer allows an instance of a class or struct to be indexed as an array.
 If the user will define an indexer for a class, then the class will behave like a virtual array.
 Array access operator i.e ([ ]) is used to access the instance of the class which uses an indexer.
Syntax:
[access_modifier] [return_type] this [argument_list] access_modifier: It can be public, private,
protected or internal.
{
return_type: It can be any valid C# type.
get this: It is the keyword which points to the object of
the current class.
{
argument_list: This specifies the parameter list of
// get block code the indexer.
get{ } and set { }: These are the accessors.
}
set
{
// set block code
}
}
Implementing Indexers
1.Multiple Index Parameters: Indexers can have multiple parameters, allowing for more complex indexing scenarios. You
can define an indexer with multiple parameters to access elements based on different criteria.
2.Indexer Overloading: Similar to methods, indexers can be overloaded in C#. This means you can define multiple
indexers with different parameter types or counts, providing different ways to access elements in the class or struct.
3.Read-Only Indexers: By omitting the set accessor in the indexer declaration, you can create read-only indexers. This
restricts the ability to modify elements through the indexer, allowing only the retrieval of values.
4.Implicit vs. Explicit Interface Implementation: Indexers can be implemented implicitly or explicitly when defined as
part of an interface. Implicit implementation is used when the indexer is defined within the class itself, while explicit
implementation is used when the indexer is implemented explicitly to resolve any naming conflicts.
5.Indexers in Collections: Indexers are commonly used in collection classes, such as dictionaries, lists, and arrays. They
provide a convenient way to access and manipulate elements within these collections based on an index or key.
6.Indexers in Custom Classes: Indexers can be implemented in custom classes to provide customized access to class
members based on an index. This allows for more intuitive and expressive interaction with instances of the class.
Important Points About Indexers:

•There are two types of Indexers i.e. One Dimensional Indexer & MultiDimensional Indexersperforming

the. The above discussed is One Dimensional Indexer.

•Indexers can be overloaded.

•These are different from Properties.

•This enables the object to be indexed in a similar way to arrays.

•A set accessor will always assign the value while the get accessor will return the value.

•“this” keyword is always used to declare an indexer.

•To define the value being assigned by the set indexer, ” value” keyword is used.

•Indexers are also known as the Smart Arrays or Parameterized Property in C#.

•Indexer can’t be a static member as it is an instance member of the class.


Delegates

 In C#, delegate is a reference to the method. It works like function pointer in C and C++. But it is objected-oriented,

secured and type-safe than function pointer.

 For static method, delegate encapsulates method only. But for instance method, it encapsulates method and instance

both.

 The best use of delegate is to use as event.

 Internally a delegate declaration defines a class which is the derived class of System.Delegate.

 Syntax for delegate declaration is −

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

For example, consider a delegate −

 public delegate int MyDelegate (string s);


Instantiating Delegates
 Once a delegate type is declared, a delegate object must be created with the new keyword and be associated with a
particular method.
 When creating a delegate, the argument passed to the new expression is written similar to a method call, but without the
arguments to the method
 For example −
public delegate void printString(string s);
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);
using System; static void Main(string[] args) {
//create delegate instances
delegate int NumberChanger(int n); NumberChanger nc1 = new NumberChanger(AddNum);
namespace DelegateAppl { NumberChanger nc2 = new NumberChanger(MultNum);

class TestDelegate { //calling the methods using the delegate objects


static int num = 10; nc1(25);
Console.WriteLine("Value of Num: {0}", getNum());
public static int AddNum(int p) { nc2(5);
num += p; Console.WriteLine("Value of Num: {0}", getNum());
return num; Console.ReadKey();
} }
public static int MultNum(int q) { }
num *= q; }
return num;
} When the above code is compiled and executed, it produces the
public static int getNum() { following result −
return num;
} Value of Num: 35
Value of Num: 175
Multicasting of a Delegate

 Delegate objects can be composed using the "+" operator.

 A composed delegate calls the two delegates it was composed from.

 Only delegates of the same type can be composed.

 The "-" operator can be used to remove a component delegate from a composed delegate.

 Using this property of delegates you can create an invocation list of methods that will be called when a delegate is

invoked.

 This is called multicasting of a delegate


using System;
nc = nc1;
delegate int NumberChanger(int n);
nc += nc2;
namespace DelegateAppl {
class TestDelegate {
//calling multicast
static int num = 10;
nc(5);
Console.WriteLine("Value of Num: {0}",
public static int AddNum(int p) {
getNum());
num += p;
Console.ReadKey();
return num;
}
}
}
public static int MultNum(int q) {
num *= q;
When the above code is compiled and executed, it
return num;
produces the following result −
}
public static int getNum() {
Value of Num: 75
return num;
}
static void Main(string[] args) {
//create delegate instances
NumberChanger nc;
NumberChanger nc1 = new NumberChanger(AddNum);
NumberChanger nc2 = new NumberChanger(MultNum);
Events

 Events are user actions such as key press, clicks, mouse movements, etc., or some occurrence such as system generated

notifications.

 Applications need to respond to events when they occur.

Using Delegates with Events

 The events are declared and raised in a class and associated with the event handlers using delegates within the same class

or some other class.

 The class containing the event is used to publish the event.

 This is called the publisher class.

 Some other class that accepts this event is called the subscriber class.

 Events use the publisher-subscriber model.


Declaring Events
To declare an event inside a class, first of all, you must declare a delegate type for the even as:
public delegate string BoilerLogHandler(string str);
then, declare the event using the event keyword −
static void Main(string[] args) {
event BoilerLogHandler BoilerEventLog; EventProgram obj1 = new EventProgram();
string result = obj1.MyEvent("Tutorials
using System; Point");
Console.WriteLine(result);
namespace SampleApp { }
public delegate string MyDel(string str); }
}
class EventProgram {
event MyDel MyEvent;

public EventProgram() {
this.MyEvent += new MyDel(this.WelcomeUser);
}
public string WelcomeUser(string username) {
return "Welcome " + username;
}
Multithreading

 A thread is defined as the execution path of a program.

 Each thread defines a unique flow of control.

 If your application involves complicated and time consuming operations, then it is often helpful to set different

execution paths or threads, with each thread performing a particular job.

 However, this way the application can perform one job at a time.

 To make it execute more than one task at a time, it could be divided into smaller threads.
Thread Life Cycle

 The life cycle of a thread starts when an object of the System.Threading.

 Thread class is created and ends when the thread is terminated or completes execution.

Following are the various states in the life cycle of a thread −

The Unstarted State − It is the situation when the instance of the thread is created but the Start method is not called.

The Ready State − It is the situation when the thread is ready to run and waiting CPU cycle.

The Not Runnable State − A thread is not executable, when

 Sleep method has been called

 Wait method has been called

 Blocked by I/O operations

The Dead State − It is the situation when the thread completes execution or is aborted.
The Main Thread using System;
using System.Threading;
 In C#, the System.Threading.Thread class is used for working with threads.
namespace
MultithreadingApplication {
 It allows creating and accessing individual threads in a multithreaded application. class MainThreadProgram {
static void Main(string[] args)
 The first thread to be executed in a process is called the main thread. {
Thread th =
Thread.CurrentThread;
 When a C# program starts execution, the main thread is automatically created. th.Name = "MainThread";

 The threads created using the Thread class are called the child threads of the main Console.WriteLine("This is
{0}", th.Name);
Console.ReadKey();
thread. }
}
 You can access a thread using the CurrentThread property of the Thread class. }
Properties and Methods of the Thread Class

The following table shows some most commonly used properties of the Thread class −

Sr.No. Property & Description


ExecutionContext Name
CurrentContext Gets an ExecutionContext
11 Gets or sets the
Gets the current context in 6 object that contains name of the
1 information about the various
which the thread is
contexts of the current thread.
thread.
executing.

CurrentCulture IsAlive Priority


2 Gets or sets the culture for Gets a value indicating the Gets or sets a
the current thread. 7
execution status of the current
thread. 12 value indicating
CurrentPrinciple the scheduling
3
Gets or sets the thread's IsBackground priority of a
current principal (for role-
8
Gets or sets a value indicating thread.
based security). whether or not a thread is a
background thread.
CurrentThread ThreadState
4 Gets the currently running IsThreadPoolThread
thread. Gets a value
Gets a value indicating
9 whether or not a thread
13 containing the
CurrentUICulture belongs to the managed thread states of the
Gets or sets the current pool. current thread.
culture used by the
5
Resource Manager to look ManagedThreadId
up culture-specific 10 Gets a unique identifier for the
resources at run-time. current managed thread.
Creating Threads

 Threads are created by extending the Thread class.

 The extended Thread class then calls the Start() method to begin the child thread execution.
using System;
using System.Threading;

namespace MultithreadingApplication {
class ThreadCreationProgram {
public static void CallToChildThread() {
Console.WriteLine("Child thread starts");
}
static void Main(string[] args) {
ThreadStart childref = new
ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child thread");
Thread childThread = new Thread(childref);
childThread.Start();
Console.ReadKey();
}
}
}
Managing Threads

 The Thread class provides various methods for managing threads.

 The following example demonstrates the use of the sleep() method for making a thread pause for a specific period of

time.
static void Main(string[] args) {
using System; ThreadStart childref = new
using System.Threading; ThreadStart(CallToChildThread);
Console.WriteLine("In Main: Creating the Child
namespace MultithreadingApplication { thread");
class ThreadCreationProgram {
public static void CallToChildThread() { Thread childThread = new Thread(childref);
Console.WriteLine("Child thread starts"); childThread.Start();
Console.ReadKey();
// the thread is paused for 5000 milliseconds }
int sleepfor = 5000; }
}
Console.WriteLine("Child Thread Paused for {0}
seconds", sleepfor / 1000);
Thread.Sleep(sleepfor);
Console.WriteLine("Child thread resumes");
}
Destroying Threads

 The Abort() method is used for destroying threads.

 The runtime aborts the thread by throwing a ThreadAbortException.

 This exception cannot be caught, the control is sent to the finally block, Console.WriteLine("Child Thread
Completed");
using System; } catch (ThreadAbortException e) {
using System.Threading; Console.WriteLine("Thread Abort
Exception");
namespace MultithreadingApplication { } finally {
class ThreadCreationProgram { Console.WriteLine("Couldn't catch
public static void CallToChildThread() { the Thread Exception");
try { }
Console.WriteLine("Child thread starts"); }
static void Main(string[] args) {
// do some work, like counting to 10 ThreadStart childref = new
for (int counter = 0; counter <= 10; counter++) { ThreadStart(CallToChildThread);
Thread.Sleep(500); Console.WriteLine("In Main: Creating
Console.WriteLine(counter); the Child thread");
}
Thread childThread = new Thread(childref);
childThread.Start(); When the above code is compiled and executed, it
produces the following result −
//stop the main thread for some time
Thread.Sleep(2000); In Main: Creating the Child thread
Child thread starts
//now abort the child 0
Console.WriteLine("In Main: Aborting the Child 1
thread"); 2
In Main: Aborting the Child thread
childThread.Abort(); Thread Abort Exception
Console.ReadKey(); Couldn't catch the Thread Exception
}
}
}
C# Windows Forms Applications

 Windows Forms is a Graphical User Interface(GUI) class library which is bundled in .Net Framework.

 Its main purpose is to provide an easier interface to develop the applications for desktop, tablet, PCs.

 It is also termed as the WinForms.

 The applications which are developed by using Windows Forms or WinForms are known as the Windows Forms

Applications that runs on the desktop computer.

 WinForms can be used only to develop the Windows Forms Applications not web applications.

 WinForms applications can contain the different type of controls like labels, list boxes, tooltip etc.
Creating a Windows Forms Application Using Visual Studio 2017
 First, open the Visual Studio then Go to File -> New -> Project to create a new project and then select the language
as Visual C# from the left menu.
 Click on Windows Forms App(.NET Framework) in the middle of current window. After that give the project name
and Click OK.
Here the solution is like a container which contains the projects and files that may be required by the program.

After that following window will display which will be divided into three parts as follows:

Editor Window or Main Window: Here, you will work with forms and code editing. You can notice the layout of form which

is now blank. You will double click the form then it will open the code for that.

Solution Explorer Window: It is used to navigate between all items in solution. For example, if you will select a file form this

window then particular information will be display in the property window.

Properties Window: This window is used to change the different properties of the selected item in the Solution Explorer.

Also, you can change the properties of components or controls that you will add to the forms.
 Now to add the controls to your WinForms application go to Toolbox tab present in the extreme left side of Visual
Studio. Here, you can see a list of controls.
 To access the most commonly used controls go to Common Controls present in Toolbox tab.
 To run the program you can use an F5 key or Play button present in the toolbar of Visual Studio.

 To stop the program you can use pause button present in the ToolBar.

 You can also run the program by going to Debug->Start Debugging menu in the menubar.
 The Windows Forms framework provides a rich set of controls that developers can use to build applications

with. These controls are designed to provide a consistent and familiar user interface for Windows users.

Developers can customize the appearance and behavior of these controls by setting various properties and

handling events.

 To create a Windows Forms application in C#, you can use Microsoft Visual Studio, which is an integrated

development environment (IDE) that provides a visual designer to create and layout the user interface elements.

The visual designer is a drag-and-drop interface for building your UI, and you can easily configure each

control’s properties through a user-friendly interface.


 In addition to the visual designer, Visual Studio also provides a code editor that enables developers to write the C#

code for the application’s logic. Developers can handle events and perform tasks such as data validation, data

manipulation, and business logic implementation.

 Windows Forms applications are versatile and can be used to create various types of applications such as data entry,

management, and reporting applications, as well as games and multimedia applications.


Windows Forms Hierarchy

 Windows Forms is that part of the .NET Framework that supports building traditional GUI applications on the

Windows platform.

 It provides a large set of classes that make it easy to create sophisticated user interfaces.

 These classes are available to all .NET languages.


Add a control to a form (Windows Forms .NET)
 Most forms are designed by adding controls to the surface of the form to define a user interface (UI).
 A control is a component on a form used to display information or accept user input.
 The primary way a control is added to a form is through the Visual Studio Designer, but you can also manage the
controls on a form at run time through code.
Add with Designer
 Visual Studio uses the Forms Designer to design forms. There is a Controls pane which lists all the controls available
to your app. You can add controls from the pane in two ways:
Add the control by double-clicking
 When a control is double-clicked, it is automatically added to the current open form with default settings.
TextBox Controls

 In Windows forms, TextBox plays an important role.


 With the help of TextBox, the user can enter data in the application, it can be of a single line or of multiple lines.
The TextBox is a class and it is defined under System.Windows.Forms namespace.
 In C#, you can create a TextBox in two different ways:
 1. Design-Time: It is the simplest way to create a TextBox as shown in the following steps:

Step 1: Create a windows form. As shown in the below image:


Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the TextBox control from the ToolBox and drop it
on the windows form. You can place TextBox anywhere on the
windows form according to your need.

Step 3: After drag and drop you will go to the properties of the
TextBox control to modify the TextBox design according to your
requirement.
2. Run-Time: It is a little bit trickier than the above method. In // Set the foreground color of the textbox
this method, you can create your own textbox using the Mytextbox.ForeColor =
TextBox class. Color.DarkOliveGreen;

Step 1 : Create a textbox using the TextBox() constructor // Set the size of the textbox
provided by the TextBox class. Mytextbox.AutoSize = true;
// Creating textbox
TextBox Mytextbox = new TextBox(); // Set the name of the textbox
Mytextbox.Name = "text_box1";
Step 2 : After creating TextBox, set the properties of the
TextBox provided by the TextBox class. Step 3 : And last add this textbox control to
form using Add() method.
// Set location of the textbox
Mytextbox.Location = new Point(187, 51); // Add this textbox to form
this.Controls.Add(Mytextbox);
// Set background color of the textbox
Mytextbox.BackColor = Color.LightGray;
CheckBox in C#

 The CheckBox control is the part of windows form which is used to take input from the user.
 Or in other words, CheckBox control allows us to select single or multiple elements from the given list or it can
provide us options like yes or no, true or false, etc.
 It can be displayed as an image or text or both.
 The CheckBox is a class and defined under System.Windows.Forms namespace.
 In Windows form, you can create CheckBox in two different ways:

1. Design-Time: It is the simplest way to create a CheckBox


using the following steps:

Step 1: Create a windows form as shown in the below image:


Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the CheckBox control from the ToolBox and drop
it on the windows form.
You can place CheckBox anywhere on the windows form
according to your need.

Step 3: After drag and drop you will go to the properties of the
CheckBox control to modify the CheckBox design according to
your requirement.

Output:
Run-Time: It is a little bit trickier than the above method. In
this method, you can create your own checkbox
programmatically using the CheckBox class. // Set font of the checkbox
Mycheckbox.Font = new Font("Bradley Hand ITC",
Step 1: Create a checkbox using the CheckBox() constructor 12);
provided by the CheckBox class. Step 3: And last add this checkbox control to form
// Creating checkbox using Add() method.
CheckBox Mycheckbox = new CheckBox(); // Add this checkbox to form
this.Controls.Add(Mycheckbox);
Step 2: After creating CheckBox, set the properties of the
CheckBox provided by the CheckBox class.
// Set height of the checkbox
Mycheckbox.Height = 50;

// Set width of the checkbox


Mycheckbox.Width = 100;

// Set location of the checkbox


Mycheckbox.Location = new Point(229, 136);

// Set text in the checkbox


Mycheckbox.Text = "Married";
RadioButton in C#

 In Windows Forms, RadioButton control is used to select a single option among the group of the options.
 For example, select your gender from the given list, so you will choose only one option among three options like
Male or Female or Transgender.
 In C#, RadioButton is a class and it is defined under System.Windows.Forms namespace. In RadioButton, you are
allowed to display text, image, or both and when you select one radio button in a group other radio buttons
automatically clear.
 You can create RadioButton in two different ways:

 1. Design-Time: It is the easiest way to create a RadioButton control as shown in the following steps:
Step 1: Create a windows form as shown in the below image:
 Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Drag the RadioButton control from the ToolBox and
drop it on the windows form.
You are allowed to place a RadioButton control anywhere on
the windows form according to your need

Step 3: After drag and drop you will go to the properties of the
RadioButton control to modify RadioButton control according
to your requirement
2. Run-Time: It is a little bit trickier than the above method. // Add text in RadioButton
In this method, you can create a RadioButton programmatically r1.Text = "Intern";
with the help of the RadioButton class.
// Set the location of the RadioButton
The following steps show how to create a RadioButton r1.Location = new Point(286, 40);
dynamically:
// Set Font property
Step 1: Create a radio button using the RadioButton() r1.Font = new Font("Berlin Sans FB", 12);
constructor is provided by the RadioButton class.
// Creating radio button Step 3: And last add this RadioButton control to the
RadioButton r1 = new RadioButton(); form using Add() method.
// Add this radio button to the form
Step 2: After creating RadioButton, set the properties of the this.Controls.Add(r1);
RadioButton provided by the RadioButton class.
// Set the AutoSize property
r1.AutoSize = true;
GroupBox Class

 In Windows form, GroupBox is a container which contains multiple controls on it and the controls are related to
each other.
 Or in other words, GroupBox is a frame display around a group of controls with a suitable optional title. Or a
GroupBox is used to categorize the related controls in a group.
 The GroupBox class is used to represent the windows group box and also provide different types of properties,
methods, and events.
 It is defined under System.Windows.Forms namespace.
 The main use of a group box is to hold a logical group of RadioButton controls.
 In C# you can create a GroupBox in the windows form by using two different ways:

1. Design-Time: It is the easiest way to create a GroupBox as


shown in the following steps:

Step 1: Create a windows form as shown in the below image:


Visual Studio -> File -> New -> Project -> WindowsFormApp
Step 2: Next, drag and drop the GroupBox from the toolbox on
the form.

Step 3: After drag and drop you will go to the properties of the
GroupBox to modify GroupBox according to your requirement.
Run-Time: It is a little bit trickier than the above method. // Setting the size of the GroupBox
In this method, you can create a GroupBox programmatically box.Size = new Size(329, 94);
with the help of syntax provided by the GroupBox class.
// Setting text the GroupBox
The following steps show how to set the create GroupBox box.Text = "Select Gender";
dynamically:
// Setting the name of the GroupBox
Step 1: Create a GroupBox using the GroupBox() constructor is box.Name = "MyGroupbox";
provided by the GroupBox class.
// Creating a GroupBox Step 3: And last add this GroupBox control to the
GroupBox box = new GroupBox(); form and also add other controls on the GroupBox
using the following statements:
Step 2: After creating GroupBox, set the property of the
GroupBox provided by the GroupBox class. // Adding groupbox in the form
// Setting the location of the GroupBox this.Controls.Add(box);
box.Location = new Point(179, 145);
and

// Adding this control to the GroupBox


box.Controls.Add(b2);
ListBox Class
 In Windows Forms, ListBox control is used to show multiple elements in a list, from which a user can select one or

more elements and the elements are generally displayed in multiple columns.

 The ListBox class is used to represent the windows list box and also provide different types of properties, methods,

and events.

 It is defined under System.Windows.Forms namespace.

 The ListBox class contains three different types of collection classes, i.e.

 ListBox.ObjectCollection: This class holds all the elements contained in the ListBox control.

 ListBox.SelectedObjectCollection: This class holds a collection of the selected items which is a subset of the items

contained in the ListBox control.

 ListBox.SelectedIndexCollection: This class holds a collection of the selected indexes, which is a subset of the

indexes of the ListBox.ObjectCollection and these indexes specify elements that are selected.
In C# you can create a ListBox in the windows form by using
two different ways:

1. Design-Time: It is the easiest way to create a ListBox as


shown in the following steps:

Step 1: Create a windows form as shown in the below image:


Visual Studio -> File -> New -> Project -> WindowsFormApp

Step 2: Next, drag and drop the ListBox control from the
toolbox to the form.
Step 3: After drag and drop you will go to the properties of the
ListBox control to modify ListBox according to your
requirement.
2. Run-Time: It is a little bit trickier than the above method.
In this method, you can create a ListBox control Step 3: And last add this ListBox control to
programmatically with the help of syntax provided by the the form using the following statement:
ListBox class. // Adding ListBox control
The following steps show how to set the create ListBox // to the form
dynamically:

Step 1: Create a ListBox control using the ListBox() constructor


is provided by the ListBox class.
// Creating a ListBox control
ListBox mylist = new ListBox();

Step 2: After creating ListBox control, set the property of the


ListBox control provided by the ListBox class.
ListBox mylist = new ListBox();
mylist.Location = new Point(287, 109);
mylist.Size = new Size(120, 95);
mylist.ForeColor = Color.Purple;
mylist.Items.Add(123);
mylist.Items.Add(456);
mylist.Items.Add(789);
ComboBox in C#

 In Windows Forms, ComboBox provides two different features in a single control, it means ComboBox works as

both TextBox and ListBox. In ComboBox, only one item is displayed at a time and the rest of the items are

present in the drop-down menu.

 The ComboBox is a class in C# and defined under System.Windows.Forms Namespace.

 You can create ComboBox using the two different ways:

 1. Design-Time: It is the easiest method to create a ComboBox control using the following steps:

Step 1: Create a windows form as shown in the below image:


Visual Studio -> File -> New -> Project -> WindowsForm
Step 2: Drag the ComboBox control from the ToolBox and drop
it on the windows form. You are allowed to place a ComboBox
control anywhere on the windows form according to your need.

Step 3: After drag and drop you will go to the properties of the
ComboBox control to set the properties of the ComboBox
according to your need.
Run-Time: It is a little bit trickier than the above method. In this // Add items in the ComboBox
method, you can set create your own ComboBox control using mybox.Items.Add("C#");
the ComboBox class. Steps to create a dynamic ComboBox: mybox.Items.Add("Java");
mybox.Items.Add("Scala");
Step 1: Create a combobox using the ComboBox() constructor mybox.Items.Add("C");
is provided by the ComboBox class. mybox.Items.Add("C++");
// Creating combobox using ComboBox class
ComboBox mybox = new ComboBox(); Step 3: And last add this ComboBox control to
form using Add() method.
// Add this ComboBox to the form
Step 2: After creating ComboBox, set the properties of the this.Controls.Add(mybox);
ComboBox provided by the ComboBox class.
// Set the location of the ComboBox
mybox.Location = new Point(327, 77);

// Set the size of the ComboBox


mybox.Size = new Size(216, 26);
TrackBar

TrackBar control provides scrolling with a little different interface than a scrollbar.

Creating a TrackBar

 We can create a TrackBar control using a Forms designer at design-time or using the TrackBar class in code at run-time.

 To create a TrackBar control at design-time, you simply drag and drop a TrackBar control from Toolbox to a Form in
Visual Studio.

 After you drag and drop a TrackBar on a Form, the TrackBar looks like Figure 1.

 Once a TrackBar is on the Form, you can move it around and resize it using mouse and set its properties and events
 First step to create a dynamic TrackBar is to create an instance of TrackBar class. The following code snippet creates a
TrackBar control object.

 TrackBar tbar = newTrackBar();

 In the next step, you may set properties of a TrackBar control. The following code snippet sets the height and width
properties of a TrackBar.

 tbar.Height = 40;
 tbar.Width = 300;
Calendar Control in C#

 A DateTime represents an instant in time. The string representation of a datetime is culture-specific and
depends both on the conventions used for displaying date and time and its calendar. A calendar is a system of
organizing datetime units.

 CultureInfo provides information about a specific culture. The information includes the names for the culture,
the writing system, the calendar used, the sort order of strings, and formatting for dates and numbers.
GregorianCalendar is the most popular calendar and is used as the default for the culture-independent option.

 Each CultureInfo supports a set of calendars. The Calendar returns the default calendar for the culture. The
OptionalCalendars gives an array containing all the calendars supported by the culture.

 .NET supports several calendars including GregorianCalendar, HebrewCalendar, HijriCalendar,


JapaneseCalendar, JulianCalendar, or PersianCalendar.

 The .NET calendar types are located in the System.Globalization namespace.


Simple Calendar creation
<controls:Calendar></controls:Calendar>
Calendar display mode

Display mode=Month
<controls:Calendar Name="Calender1" HorizontalAlignment="Left" Height="250" Width="250"
DisplayMode="Month" VerticalAlignment="Top"></controls:Calendar>
Spin Boxes
A spin box—sometimes called a spinner control—is a collective term for the combination of a
text box with an up-down control.
Users can click arrow buttons (the up-down control) or press the UP ARROW or DOWN
ARROW key to change the value in the text box. The value ascends or descends
incrementally.
Panel In C#

Creating a Panel
We can create a Panel Control using the Forms designer at design-time or using the Panel
class in code at run-time.
Design-time
To create a Panel Control at design-time, you can drag and drop a Panel Control from the
Toolbox to a Form in Visual Studio. After you dragging and dropping a Panel Control to the
Form.
Once a Panel is on the form, you can move it around and resize it using the mouse and set
its properties and events.
Run-time

 Creating a Panel Control at run-time is merely a work of creating an instance of the Panel class, setting
its properties and adding the Panel to the form controls.

 The first step to create a dynamic Panel is to create an instance of the Panel class. The following code
snippet creates a Panel Control object.

 Panel dynamicPanel = newPanel();


 In the next step, you may set the properties of a Panel Control.

The following code snippet sets the location, size and Name properties of a Panel.

dynamicPanel.Location = new System.Drawing.Point(26, 12);


dynamicPanel.Name = "Panel1";
dynamicPanel.Size = new System.Drawing.Size(228, 200);
dynamicPanel.TabIndex = 0;
Setting Panel Properties

After you place a Panel Control on a form, the next step is to set its properties.

The easiest way to set properties is from the Properties Window. You can open the Properties window by
pressing F4 or right-clicking on a control and selecting the Properties menu item.
Adding Controls to a Panel

You can add controls to a Panel by dragging and dropping a control to the Panel. We can add controls
to a Panel at run-time by using its Add method. The following code snippet creates a Panel, creates a
TextBox and a CheckBox and adds these two controls to a Panel.

privatevoid CreateButton_Click(object sender, EventArgs e) {


Panel dynamicPanel = newPanel();
dynamicPanel.Location = new System.Drawing.Point(26, 12);
dynamicPanel.Name = "Panel1";
dynamicPanel.Size = new System.Drawing.Size(228, 200);
dynamicPanel.BackColor = Color.LightBlue;
TextBox textBox1 = newTextBox();
textBox1.Location = newPoint(10, 10);
textBox1.Text = "I am a TextBox5";
textBox1.Size = newSize(200, 30);
CheckBox checkBox1 = newCheckBox();
checkBox1.Location = newPoint(10, 50);
checkBox1.Text = "Check Me";
checkBox1.Size = newSize(200, 30);
dynamicPanel.Controls.Add(textBox1);
dynamicPanel.Controls.Add(checkBox1);
Controls.Add(dynamicPanel);
}
Tooltip In C#

Creating a Tooltip

Tooltip class represents a tooltip control. Once a Tooltip object is created, we need to call SetToolTip method
and pass a control and text. The following code snippet creates a Tooltip and attaches to a Button control using
SetToolTip method.
ToolTip toolTip1 = newToolTip();
toolTip1.ShowAlways = true;
toolTip1.SetToolTip(button1, "Click me to execute.");
Tooltip Properties
 Active - A tooltip is currently active.
 AutomaticDelay - Automatic delay for the tooltip.
 AutoPopDelay - The period of time the ToolTip remains visible if the pointer is stationary on a control with
specified ToolTip text.
 InitialDelay - Gets or sets the time that passes before the ToolTip appears.
 IsBaloon - Gets or sets a value indicating whether the ToolTip should use a balloon window.
 ReshowDelay - Gets or sets the length of time that must transpire before subsequent ToolTip windows appear
as the pointer moves from one control to another.
 ShowAlways - Displays if tooltip is displayed even if the parent control is not active.
 ToolTipIcon - Icon of tooltip window.
 ToolTipTitle - Title of tooltip window.
 UseAnimation - Represents whether an animation effect should be used when displaying the tooltip.
 UseFading - Represents whether a fade effect should be used when displaying the tooltip
The following code snippet sets some of these properties.
ToolTip buttonToolTip = newToolTip();
buttonToolTip.ToolTipTitle = "Button Tooltip";
buttonToolTip.UseFading = true;
buttonToolTip.UseAnimation = true;
buttonToolTip.IsBalloon = true;
buttonToolTip.ShowAlways = true;
buttonToolTip.AutoPopDelay = 5000;
buttonToolTip.InitialDelay = 1000;
buttonToolTip.ReshowDelay = 500;
buttonToolTip.SetToolTip(button1, "Click me to execute.");
Error Provider in a C# Windows Forms Application

The ErrorProvider alerts the user that something is wrong.

In this example I will use a Display Warning icon, Wrong icon (when an incorrect expression is entereded) or a
Tick icon depending upon the data entered in the text box so that the user can determine that data entered is
correct or incorrect.

Let's Begin as in the following:

1. Create a new Windows Forms Application.


2. Place two text boxes (for getting name and age) and three ErrorProvider controls from the toolbox.
Dialog Boxes In C#
 A dialog box in C# is a type of window, which is used to enable common communication or dialog between a
computer and its user. A dialog box is most often used to provide the user with the means for specifying how to
implement a command or to respond to a question. Windows.Form is a base class for a dialog box.

 Sometimes, in a graphical user interface, a window is used to communicate with the user or establish a dialog
between the user and the application. This additional window is called a dialog box. It may communicate
information to the user; prompt the user for a response or both.

 The simplest type of dialog box is the warning which displays a message and may require the user to
acknowledge that the message has been read, usually by clicking “OK” or a decision as to whether or not an
action should continue by clicking “OK” or “Cancel”.

 Some dialog boxes are standard like the warning message or error message. Save the file and enter the
password. These are called standard dialog boxes.

 A dialog box can also be customized. Such a dialog box is called a custom dialog box.
Dialog boxes are special forms that are non-resizable. They are also used to display the messages to the user. The
messages can be error messages, confirmation of the password, confirmation for the deletion of a particular
record, Find-Replace utility of the word etc. There are standard dialog boxes to open and save a file, select a folder,
print the documents, set the font or color for the text, etc.

MessageBox class is used to display messages to the user. The show() method is used to display a message box
with the specified text, caption, buttons, and icon. There are other overloads also available.

DialogResult res = MessageBox.Show("Are you sure you want


to Delete", "Confirmation", MessageBoxButtons.OKCancel,
MessageBoxIcon.Information);
if (res == DialogResult.OK) {
MessageBox.Show("You have clicked Ok Button");
//Some task…
}
if (res == DialogResult.Cancel) {
MessageBox.Show("You have clicked Cancel Button");
//Some task…
}

You might also like