0% found this document useful (0 votes)
16 views131 pages

C# Module

The document provides an introduction to C#, an object-oriented programming language developed by Microsoft, detailing its uses, advantages, and installation process. It covers fundamental concepts such as data types, operators, and includes multiple-choice questions for assessment. The document aims to guide beginners in understanding and starting with C# programming.

Uploaded by

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

C# Module

The document provides an introduction to C#, an object-oriented programming language developed by Microsoft, detailing its uses, advantages, and installation process. It covers fundamental concepts such as data types, operators, and includes multiple-choice questions for assessment. The document aims to guide beginners in understanding and starting with C# programming.

Uploaded by

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

Praktik Pemrograman C#

Chapter 1. C# Introduction
1.1 What is C#?

C# is pronounced "C-Sharp". It is an object-oriented programming


language created by Microsoft that runs on the .NET Framework. C# has roots
from the C family, and the language is close to other popular languages
like C++ and Java. The first version was released in year 2002. The latest
version, C# 11, was released in November 2022.

C# is used for:

• Mobile applications
• Desktop applications
• Web applications
• Web services
• Web sites
• Games
• VR
• Database applications
• And much, much more!

Why Use C#?

• It is one of the most popular programming language in the world


• It is easy to learn and simple to use
• It has a huge community support
• C# is an object oriented language which gives a clear structure to programs
and allows code to be reused, lowering development costs
• As C# is close to C, C++ and Java, it makes it easy for programmers to switch
to C# or vice versa

1.2 C# Get Started

Disusun Oleh : Kadri Yusuf [1]


Praktik Pemrograman C#

The easiest way to get started with C#, is to use an IDE. An IDE
(Integrated Development Environment) is used to edit and compile code.In our
tutorial, we will use Visual Studio Community, which is free to download
from https://visualstudio.microsoft.com/vs/community/. Applications written in
C# use the .NET Framework, so it makes sense to use Visual Studio, as the
program, the framework, and the language, are all created by Microsoft.
1.3 C# Install

Once the Visual Studio Installer is downloaded and installed, choose the .NET
workload and click on the Modify/Install button:

After the installation is complete, click on the Launch button to get started with
Visual Studio.

On the start window, choose Create a new project:

Disusun Oleh : Kadri Yusuf [2]


Praktik Pemrograman C#

Then click on the "Install more tools and features" button:

Choose "Console App (.NET Core)" from the list and click on the Next button:

Disusun Oleh : Kadri Yusuf [3]


Praktik Pemrograman C#

Enter a name for your project, and click on the Create button:

Visual Studio will automatically generate some code for your project:

Disusun Oleh : Kadri Yusuf [4]


Praktik Pemrograman C#

The code should look something like this:

Example explained

Line 1: using System means that we can use classes from the System namespace.

Line 2: A blank line. C# ignores white space. However, multiple lines makes the code
more readable.

Line 3: namespace is used to organize your code, and it is a container for classes and
other namespaces.

Line 4: The curly braces {} marks the beginning and the end of a block of code.

Disusun Oleh : Kadri Yusuf [5]


Praktik Pemrograman C#

Line 5: class is a container for data and methods, which brings functionality to your
program. Every line of code that runs in C# must be inside a class. In our example,
we named the class Program.

Line 7: Another thing that always appear in a C# program, is the Main method. Any
code inside its curly brackets {} will be executed. You don't have to understand the
keywords before and after Main. You will get to know them bit by bit while reading
this tutorial.

Line 9: Console is a class of the System namespace, which has a WriteLine() method
that is used to output/print text. In our example it will output "Hello World!".

If you omit the using System line, you would have to


write System.Console.WriteLine() to print/output text.

Note: Every C# statement ends with a semicolon;

Note: C# is case-sensitive: "MyClass" and "myclass" has different meaning.

Note: Unlike Java, the name of the C# file does not have to match the class name, but
they often do (for better organization). When saving the file, save it using a proper
name and add ".cs" to the end of the filename. To run the example above on your
computer, make sure that C# is properly installed: Go to the Get Started Chapter for
how to install C#. The output should be:

Disusun Oleh : Kadri Yusuf [6]


Praktik Pemrograman C#

Multiple Choice :

Certainly, here are 20 multiple-choice questions about the introduction to C# with


their respective answers:

Question 1: What is the primary company that developed C#?

a) IBM

b) Microsoft

c) Apple

d) Google

Answer: b) Microsoft

Question 2: C# is primarily used for which type of programming?

a) System-level programming

b) Scientific computing

c) Web development

d) Game development

Answer: c) Web development

Question 3: Which of the following is not a key feature of C#?

a) Type safety

b) Dynamic typing

c) Object-oriented

d) Managed code

Answer: b) Dynamic typing

Disusun Oleh : Kadri Yusuf [7]


Praktik Pemrograman C#

Question 4: Which component of the .NET framework provides automatic memory


management in C#?

a) Common Language Runtime (CLR)

b) .NET Core

c) Visual Studio

d) .NET Framework

Answer: a) Common Language Runtime (CLR)

Question 5: What is the primary purpose of the C# garbage collector?

a) Prevent buffer overflows

b) Manage memory allocation and deallocation

c) Provide security for the code

d) Compile C# code into machine code

Answer: b) Manage memory allocation and deallocation

Question 6: Which C# version introduced support for asynchronous programming


with the `async` and `await` keywords?

a) C# 2.0

b) C# 3.0

c) C# 5.0

d) C# 7.0

Answer: c) C# 5.0

Question 7: Which of the following is a popular IDE for C# development?

Disusun Oleh : Kadri Yusuf [8]


Praktik Pemrograman C#

a) Eclipse

b) IntelliJ IDEA

c) Visual Studio

d) NetBeans

Answer: c) Visual Studio

Question 8: Which .NET framework is used for cross-platform development in C#?

a) .NET Framework

b) .NET Standard

c) .NET Core

d) .NET Extended

Answer: c) .NET Core

Question 9: What kind of applications can be developed using C# and Xamarin?

a) Desktop applications

b) Web applications

c) Mobile applications

d) Cloud services

Answer: c) Mobile applications

Question 10: What is the name of the scripting language used in the Unity game
engine for game development in C#?

a) CScript

b) UnityScript

Disusun Oleh : Kadri Yusuf [9]


Praktik Pemrograman C#

c) C#Script

d) GameScript

Answer: b) UnityScript

Question 11: Which C# version introduced pattern matching and enhanced switch
statements?

a) C# 4.0

b) C# 6.0

c) C# 7.0

d) C# 8.0

Answer: d) C# 8.0

Question 12: Which of the following is not a C# application type?

a) IoT applications

b) Augmented Reality applications

c) Game development

d) Cloud services

Answer: b) Augmented Reality applications

Question 13: What is the purpose of the 'using' directive in a C# program?

a) Import a namespace

b) Define a class

c) Declare a variable

d) Include a comment

Disusun Oleh : Kadri Yusuf [10]


Praktik Pemrograman C#

Answer: a) Import a namespace

Question 14: Which of the following is not a benefit of C# garbage collection?

a) Improved memory management

b) Reduced risk of memory leaks

c) Increased speed of execution

d) Simplified memory cleanup

Answer: c) Increased speed of execution

Question 15: What is the primary mechanism for code execution and management
in C#?

a) Just-In-Time (JIT) compilation

b) Ahead-Of-Time (AOT) compilation

c) Interpretation

d) Assembly language

Answer: a) Just-In-Time (JIT) compilation

Question 16: Which version of C# introduced the 'record' data type for creating
immutable objects?

a) C# 5.0

b) C# 7.0

c) C# 8.0

d) C# 9.0

Answer: d) C# 9.0

Disusun Oleh : Kadri Yusuf [11]


Praktik Pemrograman C#

Question 17: Which technology is used for building cross-platform desktop


applications in C#?

a) Windows Presentation Foundation (WPF)

b) Xamarin.Forms

c) ASP.NET Core

d) Unity

Answer: b) Xamarin.Forms

Question 18: What keyword is used to declare a method that can be called without
creating an instance of its containing class?

a) static

b) public

c) virtual

d) sealed

Answer: a) static

Question 19: In C#, what is the purpose of an 'interface'?

a) To define a class's implementation details

b) To provide multiple constructors

c) To define a contract for methods that implementing classes must adhere to

d) To create a sealed class

Answer: c) To define a contract for methods that implementing classes must adhere
to

Disusun Oleh : Kadri Yusuf [12]


Praktik Pemrograman C#

Question 20: Which keyword is used in C# to create a new instance of a class?

a) new

b) this

c) class

d) object

Answer: a) new

Disusun Oleh : Kadri Yusuf [13]


Praktik Pemrograman C#

CHAPTER 2. DATA TYPES


As explained in the variables chapter, a variable in C# must be a specified data
type:

A data type specifies the size and type of variable values.

It is important to use the correct data type for the corresponding variable; to avoid
errors, to save time and memory, but it will also make your code more maintainable
and readable. The most common data types are:

Disusun Oleh : Kadri Yusuf [14]


Praktik Pemrograman C#

Numbers

Number types are divided into two groups:

Integer types stores whole numbers, positive or negative (such as 123 or -456),
without decimals. Valid types are int and long. Which type you should use, depends
on the numeric value.

Floating point types represents numbers with a fractional part, containing one or
more decimals. Valid types are float and double.

Integer Types

Int

The int data type can store whole numbers from -2147483648 to 2147483647. In
general, and in our tutorial, the int data type is the preferred data type when we
create variables with a numeric value.

Disusun Oleh : Kadri Yusuf [15]


Praktik Pemrograman C#

Long

The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807. This is used when int is not large enough to store the
value. Note that you should end the value with an "L":

Floating Point Types

You should use a floating point type whenever you need a number with a decimal,
such as 9.99 or 3.14515.

The float and double data types can store fractional numbers. Note that you should
end the value with an "F" for floats and "D" for doubles:

Scientific Numbers

A floating point number can also be a scientific number with an "e" to indicate the
power of 10:

Disusun Oleh : Kadri Yusuf [16]


Praktik Pemrograman C#

Booleans

A boolean data type is declared with the bool keyword and can only take the
values true or false:

Boolean values are mostly used for conditional testing, which you will learn more
about in a later chapter.

Characters

The char data type is used to store a single character. The character must be
surrounded by single quotes, like 'A' or 'c':

Strings

The string data type is used to store a sequence of characters (text). String values
must be surrounded by double quotes:

Disusun Oleh : Kadri Yusuf [17]


Praktik Pemrograman C#

Operators

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

Although the + operator is often used to add together two values, like in the example
above, it can also be used to add together a variable and a value, or a variable and
another variable:

Disusun Oleh : Kadri Yusuf [18]


Praktik Pemrograman C#

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations:

Disusun Oleh : Kadri Yusuf [19]


Praktik Pemrograman C#

Assignment Operators

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the value 10 to
a variable called x:

The addition assignment operator (+=) adds a value to a variable:

Disusun Oleh : Kadri Yusuf [20]


Praktik Pemrograman C#

A list of all assignment operators:

Comparison Operators

Comparison operators are used to compare two values (or variables). This is
important in programming, because it helps us to find answers and make decisions.

The return value of a comparison is either True or False. These values are known
as Boolean values, and you will learn more about them in
the Booleans and If..Else chapter.

Disusun Oleh : Kadri Yusuf [21]


Praktik Pemrograman C#

In the following example, we use the greater than operator (>) to find out if 5 is
greater than 3:

A list of all comparison operators:

Disusun Oleh : Kadri Yusuf [22]


Praktik Pemrograman C#

Multiple Choice Question Chapter 2:

Question 1: Which of the following is not a built-in data type in C#?


a) int
b) char
c) string
d) class

Answer: d) class

Question 2: What is the size of the `int` data type in C# on most platforms?
a) 4 bits
b) 8 bits
c) 16 bits
d) 32 bits

Answer: d) 32 bits

Question 3: Which data type is used to represent a single character in C#?


a) char
b) string
c) byte
d) double

Answer: a) char

Question 4: Which data type is used to store floating-point numbers with double
precision in C#?
a) float
b) double
c) decimal
d) long

Answer: b) double

Question 5: What is the maximum value that can be stored in an `int` data type in
C#?
a) 127
b) 255

Disusun Oleh : Kadri Yusuf [23]


Praktik Pemrograman C#

c) 32,767
d) 2,147,483,647

Answer: d) 2,147,483,647

Question 6: Which data type is used to store a sequence of characters in C#?


a) char
b) int
c) string
d) byte

Answer: c) string

Question 7: What is the range of values that can be stored in a `byte` data type in
C#?
a) -128 to 127
b) 0 to 255
c) -32,768 to 32,767
d) -2,147,483,648 to 2,147,483,647

Answer: b) 0 to 255

Question 8: Which data type is used to store true or false values in C#?
a) bool
b) int
c) float
d) double

Answer: a) bool

Question 9: What is the keyword for the unsigned integer data type in C#?
a) unsigned
b) uint
c) int
d) byte

Answer: b) uint

Question 10: What is the data type used for holding a 64-bit signed integer in C#?

Disusun Oleh : Kadri Yusuf [24]


Praktik Pemrograman C#

a) short
b) long
c) int
d) float

Answer: b) long

Question 11: Which data type is used to store a decimal number with higher precision
than `float` or `double`?
a) float
b) double
c) decimal
d) long

Answer: c) decimal

Question 12: What is the maximum value that can be stored in a `long` data type in
C#?
a) 127
b) 255
c) 32,767
d) 9,223,372,036,854,775,807

Answer: d) 9,223,372,036,854,775,807

Question 13: Which data type is used to store date and time values in C#?
a) date
b) time
c) datetime
d) timestamp

Answer: c) datetime

Question 14: What is the data type used for storing monetary values in C#?
a) double
b) decimal
c) float
d) currency

Disusun Oleh : Kadri Yusuf [25]


Praktik Pemrograman C#

Answer: b) decimal

Question 15: Which data type is used for holding very large whole numbers in C#?
a) int
b) double
c) decimal
d) BigInteger

Answer: d) BigInteger

Question 16: What is the default value for a `bool` data type in C# if not explicitly
assigned?
a) true
b) false
c) 0
d) null

Answer: b) false

Question 17: Which data type is used to store a single 16-bit Unicode character in
C#?
a) char
b) string
c) byte
d) wchar

Answer: a) char

Question 18: What is the data type for representing a collection of key-value pairs in
C#?
a) array
b) list
c) dictionary
d) stack

Answer: c) dictionary

Question 19: What is the data type used for holding a single 32-bit signed integer in
C#?

Disusun Oleh : Kadri Yusuf [26]


Praktik Pemrograman C#

a) short
b) long
c) int
d) float

Answer: c) int

Question 20: Which data type is used to store textual data in C#?
a) char
b) string
c) text
d) varchar

Answer: b) string

Disusun Oleh : Kadri Yusuf [27]


Praktik Pemrograman C#

Chapter 3. IF Condition

In this chapter, we’ll discuss about:


a. IF Statement
b. Nexted IF

3.1 IF Statement
If statement is a fundamental control structure used to make decisions in your
code. It allows you to execute a block of code if a specified condition is true. The code
inside the if block is skipped, and your program continues with the next statement if
the condition is false.

Here is the basic syntax of an if statement in C#:


if (condition)
{
// Code to execute if the condition is true
}

The if keyword is followed by an expression enclosed in parentheses. This expression


is the condition that you want to check. It can be any valid boolean expression that
evaluates to either true or false.
If the condition inside the parentheses evaluates to true, the code block enclosed in
curly braces { } following the if statement is executed. This code block can contain
one or more statements.
The code inside the if block is skipped, and the program continues with the next
statement after the if block if the condition is false.

Here is a simple example:

using System;

namespace IfConditionExample
{
class Program
{
static void Main(string[] args)
{
int number = 10;

Disusun Oleh : Kadri Yusuf [28]


Praktik Pemrograman C#

if (number % 2 == 0)
{
Console.WriteLine("The number is even.");
}
else
{
Console.WriteLine("The number is odd.");
}
}
}
}

You can also use an else statement to specify a block of code that should be executed
when the if condition is false. Here is an example:
int y = 3;
if (y > 5)
{
Console.WriteLine("y is greater than 5");
}
else
{
Console.WriteLine("y is not greater than 5");
}

In this case, because y is not greater than 5, the message "y is not greater than 5" will
be printed.

You can also use else if clauses to test multiple conditions in sequence:

int z = 7;
if (z > 10)
{
Console.WriteLine("z is greater than 10");
}
else if (z > 5)
{
Console.WriteLine("z is greater than 5 but not greater than 10");
}
else

Disusun Oleh : Kadri Yusuf [29]


Praktik Pemrograman C#

{
Console.WriteLine("z is not greater than 5");
}

This allows you to handle different cases based on various conditions.

3.2 Nexted IF
Nested `if` statements in C# are used when you need to create more complex
conditional logic by placing one `if` statement inside another. This allows you to test
multiple conditions in a hierarchical manner. Each `if` statement is associated with
its own block of code, and the inner `if` statements are only evaluated if the outer
`if` conditions are true.

Here is the basic syntax of a nested `if` statement:

if (outerCondition)
{
// Code to execute if the outer condition is true

if (innerCondition)
{
// Code to execute if both the outer and inner conditions are true
}
else
{
// Code to execute if the outer condition is true, but the inner condition is false
}
}
else
{
// Code to execute if the outer condition is false
}

Here is an example to illustrate the concept of nested `if` statements:

int age = 25;


bool hasLicense = true;
if (age >= 18)
{

Disusun Oleh : Kadri Yusuf [30]


Praktik Pemrograman C#

Console.WriteLine("You are eligible to apply for a driving license.");

if (hasLicense)
{
Console.WriteLine("You already have a driving license.");
}
else
{
Console.WriteLine("You can apply for a driving license.");
}
}
else
{
Console.WriteLine("You are not eligible to apply for a driving license.");
}

Explanation:
- The outer `if` statement checks if the `age` is greater than or equal to 18. If it
is true, it displays a message about eligibility for a driving license.
- Within the outer `if` block, there is a nested `if` statement that checks if the
`hasLicense` variable is `true`. If it is true, it displays a message indicating
that the person already has a driving license; otherwise, it indicates that they
can apply for one.
- If the outer `if` condition is `false`, it indicates that the person is not eligible
for a driving license.

Nested `if` statements can be nested further, allowing you to create more complex
conditional structures based on your specific requirements. However, it is important
to keep the code organized and clear to avoid confusion, and you should consider
using alternative control structures like `switch` statements or refactoring your code
if the nesting becomes too deep and complex.

Disusun Oleh : Kadri Yusuf [31]


Praktik Pemrograman C#

Disusun Oleh : Kadri Yusuf [32]


Praktik Pemrograman C#

Multiple Choice Questions 3:

Question 1: Which keyword is used to start an `if` statement in C#?


a) begin
b) then
c) if
d) condition

Answer: c) if

Question 2: What is the purpose of an `if` statement in C#?


a) To create a loop
b) To define a function
c) To execute code conditionally
d) To declare a variable

Answer: c) To execute code conditionally

Question 3: In C#, what is the result of the expression `5 > 3`?


a) True
b) False

Answer: a) True

Question 4: Which of the following operators is used to combine multiple conditions


with an `if` statement in C#?
a) &
b) ||
c) !
d) ^

Answer: b) ||

Question 5: What is the purpose of the `else` keyword in an `if` statement?


a) To check for multiple conditions
b) To create a loop
c) To specify an alternative code block to execute when the condition is false

Disusun Oleh : Kadri Yusuf [33]


Praktik Pemrograman C#

d) To define a function

Answer: c) To specify an alternative code block to execute when the condition is false

Question 6: In C#, what is the result of the expression `(7 == 3) && (4 < 6)`?
a) True
b) False

Answer: a) True

Question 7: Which C# conditional statement allows you to specify multiple


alternative code blocks to execute based on different conditions?
a) `if`
b) `switch`
c) `for`
d) `while`

Answer: b) `switch`

Question 8: What is the purpose of the `break` statement in a `switch` statement in


C#?
a) To end the program
b) To exit the loop
c) To jump to another case
d) To skip to the next condition

Answer: b) To exit the loop

Question 9: What does the `default` case do in a C# `switch` statement?


a) It is always executed.
b) It indicates the end of the `switch` statement.
c) It specifies the default condition when none of the other cases match.
d) It is used to define the first case.

Answer: c) It specifies the default condition when none of the other cases match.

Question 10: In a C# `switch` statement, what is the data type of the expression that
is evaluated?
a) string

Disusun Oleh : Kadri Yusuf [34]


Praktik Pemrograman C#

b) int
c) double
d) char

Answer: b) int

Question 11: Which C# operator is used for comparing if two values are equal?
a) =
b) ==
c) =
d) ~

Answer: b) ==

Question 12: Which of the following is the correct syntax for an `if` statement with
an `else if` condition in C#?
a)
```csharp
if (condition) {
// code block
} else (anotherCondition) {
// code block
}
```
b)
```csharp
if (condition) {
// code block
} else if (anotherCondition) {
// code block
}
```
c)
```csharp
if (condition) {
// code block
} elseif (anotherCondition) {
// code block
}

Disusun Oleh : Kadri Yusuf [35]


Praktik Pemrograman C#

```

Answer: b)
```csharp
if (condition) {
// code block
} else if (anotherCondition) {
// code block
}
```

Question 13: Which C# keyword is used to exit a loop early and continue to the next
iteration?
a) end
b) return
c) break
d) exit

Answer: c) break

Question 14: In a C# `if` statement, which of the following conditions is equivalent


to "not equal"?
a) =
b) ==
c) !=
d) <>

Answer: c) !=

Question 15: What is the purpose of the `else` if no condition is provided in an `if-
else` statement?
a) It is required.
b) It indicates the end of the `if` statement.
c) It specifies the code block to execute if the initial condition is true.
d) It is optional, and no code is executed.

Answer: c) It specifies the code block to execute if the initial condition is true.

Question 16: In C#, what does the `?` operator do?

Disusun Oleh : Kadri Yusuf [36]


Praktik Pemrograman C#

a) It is used to define a method.


b) It is used for conditional assignment.
c) It is used to perform bitwise operations.
d) It is used for type casting.

Answer: b) It is used for conditional assignment.

Question 17: What is the result of the expression `(10 > 5) ? "Yes" : "No"` in C#?
a) "Yes"
b) "No"

Answer: a) "Yes"

Question 18: In C#, which of the following is a valid way to combine multiple
conditions using the `AND` logic?
a) &&
b) ||
c) !
d) &

Answer: a) &&

Question 19: What is the purpose of the `return` statement in a C# method?


a) To exit the program
b) To indicate the end of the method
c) To return a value and exit the method
d) To define a loop

Answer: c) To return a value and exit the method

Question 20: In a C# `if` statement, which code block is executed when the condition
is true?
a) Both the `if` and `else` blocks.
b) Neither block.
c) Only the `if` block.
d) Only the `else` block.

Answer: c) Only the `if` block.

Disusun Oleh : Kadri Yusuf [37]


Praktik Pemrograman C#

References:

1. If Statement in JavaScript (tutorjoes.in)

Disusun Oleh : Kadri Yusuf [38]


Praktik Pemrograman C#

Chapter 4. Looping
Looping is a fundamental concept in programming that allows you to
repeatedly execute a block of code as long as a specific condition is met or for a
predetermined number of times. In C#, there are several looping constructs to achieve
this:

4.1 For Loop


The `for` loop is commonly used when you know in advance how many times you
want to execute a block of code. It consists of three parts: initialization, condition, and
iterator.
for (int i = 0; i < 5; i++)
{
// Code to be executed repeatedly
}
In this example, the loop initializes `i` to 0, executes the code block while `i` is less
than 5, and increments `i` by 1 in each iteration.

4.2 While Loop


The while loop repeatedly executes a block of code as long as a specified
condition is `true`. It is suitable when you don't know in advance how many iterations
are needed.
int count = 0;
while (count < 5)
{
// Code to be executed repeatedly
count++;
}
This loop will execute the code block as long as `count` is less than 5.

4.3 Do-while Loop


The `do-while` loop is similar to the `while` loop, but it ensures that the code block
is executed at least once before checking the condition.
int count = 0;
do
{
// Code to be executed repeatedly
count++;

Disusun Oleh : Kadri Yusuf [39]


Praktik Pemrograman C#

}
while (count < 5);
In this example, the code block will be executed at least once, even if `count` is
initially not less than 5.

4.4 Foreach Loop


The `foreach` loop is used for iterating over collections (arrays, lists, etc.) without
worrying about indexing. It iterates through each element in the collection.
int[] numbers = { 1, 2, 3, 4, 5 };
foreach (int num in numbers)
{
// Code to be executed for each element in the array
}
This loop will iterate through each element in the `numbers` array and execute the
code block for each element.

4.5 Break and continue Statements


Inside loops, you can use the `break` statement to exit the loop prematurely
when a certain condition is met, and the `continue` statement to skip the rest of the
current iteration and move to the next iteration.
for (int i = 0; i < 10; i++)
{
if (i == 5)
{
break; // Exit the loop when i is 5
}
if (i % 2 == 0)
{
continue; // Skip even numbers
}
// Code to be executed
}

Looping is a powerful way to perform repetitive tasks in your programs, and choosing
the appropriate loop construct depends on your specific requirements and the
structure of your data. It's important to ensure that the loop's conditions are properly
managed to avoid infinite loops or unexpected behaviour.

Disusun Oleh : Kadri Yusuf [40]


Praktik Pemrograman C#

Multiple Choice Questions in Chapter 4:

Question 1: Which looping construct in C# is used for executing a block of code


while a condition is true?

a) `for`

b) `do-while`

c) `foreach`

d) `while`

Answer: d) `while`

Question 2: In a `for` loop, what is the purpose of the initialization statement?

a) To set the condition for loop termination

b) To declare a new variable

c) To initialize the loop control variable

d) To print the loop index

Answer: c) To initialize the loop control variable

Question 3: Which looping construct in C# is guaranteed to execute the loop body


at least once?

a) `for`

b) `do-while`

c) `foreach`

d) `while`

Answer: b) `do-while`

Disusun Oleh : Kadri Yusuf [41]


Praktik Pemrograman C#

Question 4: In a `foreach` loop, what is the primary purpose?

a) To count iterations

b) To repeat a block of code a specified number of times

c) To iterate over elements in a collection

d) To execute a loop with a known number of iterations

Answer: c) To iterate over elements in a collection

Question 5: In a `for` loop, which statement is typically used to modify the loop
control variable?

a) The `if` statement

b) The `return` statement

c) The increment/decrement statement

d) The `break` statement

Answer: c) The increment/decrement statement

Question 6: Which of the following loop constructs is best suited for iterating over
an array or a collection?

a) `for`

b) `do-while`

c) `foreach`

d) `while`

Answer: c) `foreach`

Question 7: What is the purpose of the `break` statement in a loop?

a) To restart the loop from the beginning

Disusun Oleh : Kadri Yusuf [42]


Praktik Pemrograman C#

b) To end the program

c) To exit the loop prematurely

d) To increment the loop counter

Answer: c) To exit the loop prematurely

Question 8: In a `while` loop, when is the loop condition checked?

a) Before executing the loop body

b) After executing the loop body

c) It is never checked

d) Only once, at the start

Answer: a) Before executing the loop body

Question 9: In a `for` loop, where is the loop control variable usually declared?

a) Before the loop

b) Inside the loop body

c) In the initialization statement

d) After the loop

Answer: a) Before the loop

Question 10: What is the purpose of the `continue` statement in a loop?

a) To terminate the loop

b) To skip the rest of the current iteration and continue with the next

c) To go back to the start of the loop

d) To execute the loop body one more time

Disusun Oleh : Kadri Yusuf [43]


Praktik Pemrograman C#

Answer: b) To skip the rest of the current iteration and continue with the next

Question 11: Which keyword is used to exit the current iteration of a loop and
proceed to the next iteration in C#?

a) `skip`

b) `next`

c) `break`

d) `continue`

Answer: d) `continue`

Question 12: In a `do-while` loop, when is the loop condition checked?

a) Before executing the loop body

b) After executing the loop body

c) It is never checked

d) Only once, at the start

Answer: b) After executing the loop body

Question 13: What is the primary purpose of a loop counter variable in a `for` loop?

a) To initialize the loop

b) To define a variable

c) To control the number of loop iterations

d) To execute the loop body

Answer: c) To control the number of loop iterations

Disusun Oleh : Kadri Yusuf [44]


Praktik Pemrograman C#

Question 14: In a `while` loop, what is the first thing that happens during each
iteration?

a) The loop condition is checked

b) The loop body is executed

c) The loop control variable is incremented

d) The loop is terminated

Answer: a) The loop condition is checked

Question 15: What is the primary use of a `foreach` loop in C#?

a) To execute code a specified number of times

b) To iterate over elements in an array or collection

c) To count the number of elements in an array

d) To declare variables

Answer: b) To iterate over elements in an array or collection

Question 16: In a `do-while` loop, under what conditions will the loop continue to
execute?

a) As long as the loop control variable is less than a certain value

b) As long as the loop condition is true

c) As long as the loop control variable is incremented

d) As long as the loop condition is false

Answer: b) As long as the loop condition is true

Question 17: What does the `return` statement do in a loop?

Disusun Oleh : Kadri Yusuf [45]


Praktik Pemrograman C#

a) It exits the loop.

b) It skips the rest of the current iteration.

c) It restarts the loop.

d) It terminates the program.

Answer: a) It exits the loop.

Question 18: In a `for` loop, what is the order in which the loop statements are
executed?

a) Initialization, condition check, increment/decrement

b) Condition check, increment/decrement, initialization

c) Increment/decrement, condition check, initialization

d) Condition check, initialization, increment/decrement

Answer: a) Initialization, condition check, increment/decrement

Question 19: Which looping construct in C# is ideal for when the number of
iterations is unknown and determined dynamically?

a) `for`

b) `do-while`

c) `foreach`

d) `while`

Answer: d) `while`

Question 20: What is the purpose of the `do` keyword in a `do-while` loop in C#?

a) To define the loop condition

b) To specify the loop body

Disusun Oleh : Kadri Yusuf [46]


Praktik Pemrograman C#

c) To indicate the end of the loop

d) To repeat the loop

Answer: b) To specify the loop body

Disusun Oleh : Kadri Yusuf [47]


Praktik Pemrograman C#

Chapter 5. Array & Collection


5.1 C# Arrays

An array stores a fixed-size sequential collection of elements of the same type.


An array is used to store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type stored at contiguous memory
locations.
Instead of declaring individual variables, such as number0, number1, ..., and
number99, you declare one array variable such as numbers and use numbers[0],
numbers[1], and ..., numbers[99] to represent individual variables. A specific element
in an array is accessed by an index. All arrays consist of contiguous memory locations.
The lowest address corresponds to the first element and the highest address to the
last element.

5.1.1 Declaring Array Types


To declare an array in C#, you can use the following syntax –

datatype[] arrayName;
where,
• datatype is used to specify the type of elements in the array.
• [ ] specifies the rank of the array. The rank specifies the size of the array.
• arrayName specifies the name of the array.
For example,

double[] balance;

5.1.2 Initializing an Array

Declaring an array does not initialize the array in the memory. When the array
variable is initialized, you can assign values to the array. Array is a reference type, so
you need to use the new keyword to create an instance of the array. For example,

Disusun Oleh : Kadri Yusuf [48]


Praktik Pemrograman C#

double[] balance = new double[10];

5.1.3 Using the foreach Loop

In the previous example, we used a for loop for accessing each array element.
You can also use a foreach statement to iterate through an array.

using System;

namespace ArrayApplication {
class MyArray {
static void Main(string[] args) {
int [] n = new int[10]; /* n is an array of 10 integers */

/* initialize elements of array n */


for ( int i = 0; i < 10; i++ ) {
n[i] = i + 100;
}

/* output each array element's value */


foreach (int j in n ) {
int i = j-100;
Console.WriteLine("Element[{0}] = {1}", i, j);
}
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following
result –

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

Disusun Oleh : Kadri Yusuf [49]


Praktik Pemrograman C#

5.2 Collection
Collections are an essential part of the language and are used to store,
manage, and manipulate groups of objects. Collections provide various data
structures and classes to work with different types of data efficiently. Here are some
of the most commonly used collections in C#:

5.2.1 Arrays

Arrays are fixed-size collections that can hold elements of the same data type.
They have a fixed length and are suitable when you know the number of elements in
advance.

int[] numbers = new int[5];

numbers[0] = 1;

numbers[1] = 2;

// ...

Example:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace Project5_2

internal class Program

static void Main(string[] args)

int[] numbers = new int[5];

numbers[0] = 1;

Disusun Oleh : Kadri Yusuf [50]


Praktik Pemrograman C#

numbers[1] = 2;

numbers[2] = 3;

numbers[3] = 4;

numbers[4] = 5;

for(int i = 0; i < 5; i++)

Console.WriteLine(numbers[i]);

5.2.2 List<T>
List<T> is a dynamic array that can grow or shrink in size. It's part of the
System.Collections.Generic namespace and provides various methods for adding,
removing, and manipulating elements.

List<int> numbers = new List<int>();

numbers.Add(1);

numbers.Add(2);

// ...

Example:

using System.Collections.Generic;

using System;

class Program

static void Main(string[] args)

Disusun Oleh : Kadri Yusuf [51]


Praktik Pemrograman C#

// Create a List of integers

List<int> numbers = new List<int>();

// Add elements to the list

numbers.Add(10);

numbers.Add(20);

numbers.Add(30);

// Access elements by index

int firstNumber = numbers[0]; // 10

// Remove an element

numbers.Remove(20);

// Check if an element exists

bool contains30 = numbers.Contains(30); // true

// Iterate through the list

Console.WriteLine("List of Numbers:");

foreach (int num in numbers)

Console.WriteLine(num);

Console.ReadLine();

5.2.3 Dictionary <TKey, TValue>

A Dictionary is a collection of key-value pairs. It allows you to store and retrieve


values based on a unique key.

Dictionary<string, int> ageMap = new Dictionary<string, int>();

ageMap["Alice"] = 30;

Disusun Oleh : Kadri Yusuf [52]


Praktik Pemrograman C#

ageMap["Bob"] = 25;

// ...

Example:

class Program

static void Main(string[] args)

// Create a Dictionary with string keys and int values

Dictionary<string, int> studentGrades = new Dictionary<string, int>();

// Add key-value pairs to the dictionary

studentGrades["Alice"] = 90;

studentGrades["Bob"] = 85;

studentGrades["Charlie"] = 78;

// Access values by key

int aliceGrade = studentGrades["Alice"]; // 90

// Check if a key exists

bool hasCharlie = studentGrades.ContainsKey("Charlie"); // true

// Iterate through the dictionary

Console.WriteLine("Student Grades:");

foreach (var kvp in studentGrades)

Console.WriteLine($"{kvp.Key}: {kvp.Value}");

Console.ReadLine();

Disusun Oleh : Kadri Yusuf [53]


Praktik Pemrograman C#

5.2.4 HashSet<T>

A HashSet is an unordered collection of unique elements. It is useful when you


need to ensure that elements are distinct.

HashSet<int> uniqueNumbers = new HashSet<int>();

uniqueNumbers.Add(1);

uniqueNumbers.Add(2);

// ...

Example:

class Program

static void Main(string[] args)

// Create a HashSet of unique names

HashSet<string> uniqueNames = new HashSet<string>();

// Add elements to the HashSet

uniqueNames.Add("Alice");

uniqueNames.Add("Bob");

uniqueNames.Add("Charlie");

// Attempt to add a duplicate element (it won't be added)

bool addedDuplicate = uniqueNames.Add("Alice");

// Check if an element exists

bool containsBob = uniqueNames.Contains("Bob"); // true

// Remove an element

bool removedCharlie = uniqueNames.Remove("Charlie");

// Iterate through the HashSet

Console.WriteLine("Unique Names:");

foreach (string name in uniqueNames)

Disusun Oleh : Kadri Yusuf [54]


Praktik Pemrograman C#

Console.WriteLine(name);

Console.ReadLine();

5.2.5 Queue

A Queue is a collection that follows the First-In-First-Out (FIFO) principle. It is


suitable for implementing tasks like a queue of items waiting to be processed.

Queue<string> taskQueue = new Queue<string>();

taskQueue.Enqueue("Task 1");

taskQueue.Enqueue("Task 2");

// ...

Example:

class Program

static void Main(string[] args)

// Create a Queue of strings

Queue<string> messages = new Queue<string>();

// Enqueue (add) items to the queue

messages.Enqueue("Message 1");

messages.Enqueue("Message 2");

messages.Enqueue("Message 3");

// Dequeue (remove and retrieve) items from the queue

string message1 = messages.Dequeue(); // "Message 1"

string message2 = messages.Dequeue(); // "Message 2"

Disusun Oleh : Kadri Yusuf [55]


Praktik Pemrograman C#

// Peek at the front of the queue without removing

string peekedMessage = messages.Peek(); // "Message 3"

// Check if the queue contains an item

bool containsMessage3 = messages.Contains("Message 3"); // true

// Iterate through the queue

Console.WriteLine("Messages in Queue:");

foreach (string message in messages)

Console.WriteLine(message);

Console.ReadLine();

5.2.6 Stack

A Stack is a collection that follows the Last-In-First-Out (LIFO) principle. It's


often used for tasks like maintaining a history or undo functionality.

Stack<string> historyStack = new Stack<string>();

historyStack.Push("Page 1");

historyStack.Push("Page 2");

// ...

Example:

using System;

using System.Collections.Generic;

class Program

static void Main()

Disusun Oleh : Kadri Yusuf [56]


Praktik Pemrograman C#

// Create a new stack of integers

Stack<int> myStack = new Stack<int>();

// Push elements onto the stack

myStack.Push(1);

myStack.Push(2);

myStack.Push(3);

// Pop elements from the stack

int poppedItem1 = myStack.Pop();

int poppedItem2 = myStack.Pop();

int poppedItem3 = myStack.Pop();

// Check if the stack is empty

bool isEmpty = myStack.Count == 0;

Console.WriteLine($"Popped items: {poppedItem1}, {poppedItem2},


{poppedItem3}");

Console.WriteLine($"Is the stack empty? {isEmpty}");

5.2.7 ArrayList

While not recommended for new code (consider using List<T> instead),
ArrayList is a non-generic collection that can hold elements of different data types.
It's part of the System.Collections namespace.

ArrayList mixedList = new ArrayList();

mixedList.Add(1);

mixedList.Add("Hello");

// ...

Example:

using System;

using System.Collections;

Disusun Oleh : Kadri Yusuf [57]


Praktik Pemrograman C#

class Program

static void Main()

// Create a new ArrayList

ArrayList myArrayList = new ArrayList();

// Add elements to the ArrayList

myArrayList.Add(1);

myArrayList.Add("Hello");

myArrayList.Add(3.14);

// Access elements in the ArrayList

Console.WriteLine("Elements in the ArrayList:");

foreach (var item in myArrayList)

Console.WriteLine(item);

// Remove an element from the ArrayList

myArrayList.Remove("Hello");

// Check if an element exists in the ArrayList

bool containsElement = myArrayList.Contains(3.14);

Console.WriteLine($"Does the ArrayList contain 3.14? {containsElement}");

// Get the index of an element in the ArrayList

int indexOfElement = myArrayList.IndexOf(1);

Console.WriteLine($"Index of 1 in the ArrayList: {indexOfElement}");

5.2.8 LinkedList<T>:

Disusun Oleh : Kadri Yusuf [58]


Praktik Pemrograman C#

A LinkedList is a collection that represents a doubly-linked list. It allows


efficient insertion and removal of elements at any position in the list.

LinkedList<int> linkedList = new LinkedList<int>();

linkedList.AddLast(1);

linkedList.AddLast(2);

// ...

Example:

using System;

using System.Collections.Generic;

class Program

static void Main()

// Create a new LinkedList of integers

LinkedList<int> myLinkedList = new LinkedList<int>();

// Add elements to the LinkedList

myLinkedList.AddLast(1);

myLinkedList.AddLast(2);

myLinkedList.AddLast(3);

// Iterate through the LinkedList

Console.WriteLine("Elements in the LinkedList:");

foreach (int item in myLinkedList)

Console.WriteLine(item);

// Remove an element from the LinkedList

Disusun Oleh : Kadri Yusuf [59]


Praktik Pemrograman C#

myLinkedList.Remove(2);

// Check if an element exists in the LinkedList

bool containsElement = myLinkedList.Contains(3);

Console.WriteLine($"Does the LinkedList contain 3? {containsElement}");

// Add an element before a specific element

LinkedListNode<int> node = myLinkedList.Find(3);

myLinkedList.AddBefore(node, 4);

// Iterate through the LinkedList again

Console.WriteLine("Elements in the LinkedList after modifications:");

foreach (int item in myLinkedList)

Console.WriteLine(item);

These are some of the commonly used collection types in C#. Each has its own
advantages and use cases, so choosing the right one depends on the specific
requirements of your application. C# collections are part of the .NET Framework and
provide powerful tools for working with data in various ways.

Disusun Oleh : Kadri Yusuf [60]


Praktik Pemrograman C#

Multiple Choice Questions in Chapter 5:

1. What is an array in C#?


a. A collection of elements with different data types.
b. A collection of elements with the same data type, stored in a contiguous
memory location.
c. A collection of key-value pairs.
d. A collection of elements sorted in ascending order.

Answer: b) A collection of elements with the same data type, stored in a


contiguous memory location.

2. How do you declare an integer array named `numbers` with a size of 5 in C#?
a. `int[] numbers = new int[5];`
b. `int numbers[5];`
c. `int[5] numbers;`
d. `int numbers = [5];`

Answer: a) `int[] numbers = new int[5];`

3. In C#, what is the index of the first element in an array?


a. 0
b. 1
c. -1
d. The index is determined by the size of the array.

Answer: a) 0

4. Which of the following is true about C# arrays?


a. Arrays can change in size dynamically.
b. Arrays can store elements of different data types.
c. Arrays are reference types.
d. Arrays automatically sort their elements in ascending order.

Answer: c) Arrays are reference types.

5. What is the maximum number of dimensions an array can have in C#?


a. 1
b. 2
c. 3
d. There is no fixed limit.

Answer: d) There is no fixed limit.

6. How do you access the element at index 3 in an array named `myArray` in C#?

Disusun Oleh : Kadri Yusuf [61]


Praktik Pemrograman C#

a. `myArray[3]`
b. `myArray(3)`
c. `myArray{3}`
d. `myArray.at(3)`

Answer: a) `myArray[3]`

7. What happens if you try to access an array element with an index that is out of
bounds in C#?
a. An exception is thrown at runtime.
b. The element is set to null.
c. The array is automatically resized.
d. The program compiles successfully but produces unexpected results.

Answer: a) An exception is thrown at runtime.

8. How do you get the length (number of elements) of an array in C#?


a. `array.length`
b. `array.size()`
c. `array.Length`
d. `array.Count()`

Answer: c) `array.Length`

9. What is the purpose of the `foreach` loop in C# when working with arrays?
a. It allows you to iterate through the array in reverse order.
b. It provides a way to modify array elements in place.
c. It simplifies the process of iterating through all elements in the array.
d. It is used to create a copy of the array.

Answer: c)

10. In C#, what is the term for an array where each element is itself an array?
a. Multi-dimensional array
b. Jagged array
c. Linked array
d. Dynamic array

Answer: b) Jagged array

11. Which C# collection type is suitable for storing elements of the same data type in
a dynamically-sized array?
a. Array
b. List<T>
c. Dictionary<TKey, TValue>

Disusun Oleh : Kadri Yusuf [62]


Praktik Pemrograman C#

d. HashSet<T>

Answer: b) List<T>

12. What is the primary advantage of using a HashSet<T> collection in C#?


a. It allows duplicate elements.
b. It maintains elements in sorted order.
c. It ensures that all elements are unique.
d. It follows the Last-In-First-Out (LIFO) principle.

Answer: c) It ensures that all elements are unique.

13. Which C# collection type is ideal for implementing a task queue where elements
are processed in the order they are added?
a. List<T>
b. Dictionary<TKey, TValue>
c. HashSet<T>
d. Queue<T>

Answer: d) Queue<T>

14. In C#, which collection type allows efficient insertion and removal of elements at
both ends and is often used as a double-ended queue?
a. List<T>
b. Dictionary<TKey, TValue>
c. HashSet<T>
d. LinkedList<T>

Answer: d) LinkedList<T>

15. Which C# collection follows the First-In-First-Out (FIFO) principle?


a. List<T>
b. Dictionary<TKey, TValue>
c. HashSet<T>
d. Queue<T>

Answer: d) Queue<T>

16. What is the key difference between a List<T> and an ArrayList in C#?
a. List<T> is generic, whereas ArrayList is not.
b. List<T> allows for better type safety and performance.
c. ArrayList is a dynamically-sized array.
d. List<T> can store elements of different data types, whereas ArrayList cannot.

Answer: a) List<T> is generic, whereas ArrayList is not.

Disusun Oleh : Kadri Yusuf [63]


Praktik Pemrograman C#

17. In C#, which collection type is used to store a collection of key-value pairs?
a. List<T>
b. Dictionary<TKey, TValue>
c. HashSet<T>
d. LinkedList<T>

Answer: b) Dictionary<TKey, TValue>

18. Which collection type in C# represents a last-in-first-out (LIFO) data structure?


a. List<T>
b. Dictionary<TKey, TValue>
c. HashSet<T>
d. Stack<T>

Answer: d) Stack<T>

19. What C# collection type should you use when you need to store elements in
sorted order?
a. List<T>
b. Dictionary<TKey, TValue>
c. HashSet<T>
d. SortedSet<T>

Answer: d) SortedSet<T>

20. Which C# collection is not type-safe and can store elements of different data
types?
a. List<T>
b. Dictionary<TKey, TValue>
c. HashSet<T>
d. ArrayList

Answer: d) ArrayList

Disusun Oleh : Kadri Yusuf [64]


Praktik Pemrograman C#

Chapter 6. Sorting and Searching

6.1 Sorting

Sorting refers to the process of arranging elements in a collection or an array


in a specific order, such as ascending or descending. C# provides various methods
and algorithms for sorting data. In this explanation, we'll cover the most commonly
used methods and provide examples to illustrate how sorting works in C#.

6.1.1 Array.Sort Method

The `Array.Sort` method is one of the simplest ways to sort an array of


elements in C#. It is primarily used for sorting arrays of value types or reference types
that implement the `IComparable` interface. The `IComparable` interface allows
objects to define their own comparison logic.

Here's a basic example of using `Array.Sort` to sort an array of integers in ascending


order:

int[] numbers = { 5, 2, 9, 1, 5 };

Array.Sort(numbers); // Sorts the array in ascending order

You can also sort arrays of other types as long as they implement `IComparable`. For
custom classes, you can implement the `IComparable` interface to define the sorting
logic for instances of your class.

6.1.2 List<T>.Sort Method

The `List<T>.Sort` method is similar to `Array.Sort`, but it is used for sorting


generic lists (`List<T>`) instead of arrays. Here's an example of sorting a list of
strings in ascending order:

List<string> names = new List<string> { " David ", "Bob", "Charlie", " Alice" };

names.Sort(); // Sorts the list in ascending order

Again, for custom classes, you can implement the `IComparable` interface to enable
sorting using `List<T>.Sort`.

Disusun Oleh : Kadri Yusuf [65]


Praktik Pemrograman C#

6.1.3 Custom Sorting with Comparers

Sometimes, you may need to sort elements in a custom way that is not covered
by the default comparison logic provided by `IComparable`. In such cases, you can
use the `Comparison<T>` delegate or create custom comparer classes that
implement the `IComparer<T>` interface.

Using `Comparison<T>`

using System;

using System.Collections.Generic;

class Program

static void Main()

// Create a list of integers

List<int> numbers = new List<int> { 5, 3, 8, 1, 7 };

// Using the Sort method to compare and sort the list

numbers.Sort();

Console.WriteLine("Sorted numbers in ascending order:");

foreach (int number in numbers)

Console.Write(number + " ");

Console.WriteLine();

// Using the Sort method with a custom comparison to sort in descending order

numbers.Sort((a, b) => b.CompareTo(a));

Console.WriteLine("Sorted numbers in descending order:");

foreach (int number in numbers)

Disusun Oleh : Kadri Yusuf [66]


Praktik Pemrograman C#

Console.Write(number + " ");

Console.WriteLine();

6.1.4 LINQ Sorting

C# also provides sorting capabilities through Language-Integrated Query


(LINQ). You can use the `OrderBy` and `OrderByDescending` methods to sort
collections in ascending or descending order, respectively. This approach is more
expressive and works well with LINQ queries:

List<Person> people = new List<Person>

new Person { Name = "Alice", Age = 30 },

new Person { Name = "Bob", Age = 25 },

new Person { Name = "Charlie", Age = 35 }

};

var sortedPeople = people.OrderBy(p => p.Age); // Sorts by age in ascending order

6.2 Searching

Searching in C# programming refers to the process of finding a specific


element or item within a collection, such as an array, list, or other data structure. C#
provides several ways to perform searching operations efficiently. In this
comprehensive explanation, we'll explore various searching techniques in C#:

6.2.1 Linear Search

Linear search is the simplest and most straightforward searching technique. It


involves checking each element in the collection one by one until the target element
is found. Linear search works well for small collections but becomes inefficient for
large `.

Disusun Oleh : Kadri Yusuf [67]


Praktik Pemrograman C#

int[] numbers = { 5, 2, 9, 1, 7 };

int target = 9;

for (int i = 0; i < numbers.Length; i++)

if (numbers[i] == target)

// Element found at index i

break;

6.2.2 Binary Search

Binary search is a more efficient search algorithm, but it requires that the
collection be sorted. It repeatedly divides the collection in half and compares the
target element with the middle element. Binary search has a time complexity of O(log
n), making it suitable for large, sorted collections.

int[] sortedNumbers = { 1, 2, 5, 7, 9 };

int target = 5;

int left = 0;

int right = sortedNumbers.Length - 1;

while (left <= right)

int mid = left + (right - left) / 2;

if (sortedNumbers[mid] == target)

// Element found at index mid

break;

else if (sortedNumbers[mid] < target)

Disusun Oleh : Kadri Yusuf [68]


Praktik Pemrograman C#

left = mid + 1;

else

right = mid - 1;

6.2.3 Searching in Lists and Collections

When working with lists or collections, you can use LINQ methods for
searching. The `Find` and `FindAll` methods are commonly used for this purpose.

List<string> names = new List<string> { "Alice", "Bob", "Charlie", "David" };

string target = "Charlie";

string result = names.Find(name => name == target);

6.2.4 Dictionary

A `Dictionary<TKey, TValue>` in C# allows you to search for values based on


their associated keys. Dictionary lookups are very efficient, usually with a time
complexity of O(1).

Dictionary<string, int> ageMap = new Dictionary<string, int>

{ "Alice", 30 },

{ "Bob", 25 },

{ "Charlie", 35 }

};

string target = "Bob";

if (ageMap.ContainsKey(target))

Disusun Oleh : Kadri Yusuf [69]


Praktik Pemrograman C#

int age = ageMap[target];

// Use age

6.2.5 HashSet

A `HashSet<T>` is useful for membership testing and searching for unique


elements. It provides quick lookups with O(1) time complexity.

HashSet<string> namesSet = new HashSet<string> { "Alice", "Bob", "Charlie",


"David" };

string target = "Charlie";

if (namesSet.Contains(target))

// Element found in the set

6.2.6 Regular Expressions

When searching for patterns within text, regular expressions


(`System.Text.RegularExpressions`) are powerful tools. They allow you to perform
complex string matching and searching operations.

using System.Text.RegularExpressions;

string text = "The quick brown fox jumped over the lazy dog.";

string pattern = "fox";

MatchCollection matches = Regex.Matches(text, pattern);

foreach (Match match in matches)

// Process each match

Disusun Oleh : Kadri Yusuf [70]


Praktik Pemrograman C#

In summary, C# offers a variety of searching techniques, from simple linear searches


to more efficient binary searches, depending on your data and requirements. The
choice of the search method should consider factors like data size, data organization
(e.g., sorted or unsorted), and specific searching needs.

Disusun Oleh : Kadri Yusuf [71]


Praktik Pemrograman C#

Exercise 6:

1. What is sorting in C# programming?

a) Grouping elements into collections

b) Arranging elements in a specific order

c) Filtering elements from a collection

d) Counting the number of elements in a collection

Answer: b) Arranging elements in a specific order

2. Which C# method is commonly used to sort an array of elements in ascending


order?

a) Array.Order

b) Array.Sort

c) Array.Swap

d) Array.Find

Answer: b) Array.Sort

3. What is the time complexity of the binary search algorithm in C#?

a) O(1)

b) O(n)

c) O(log n)

d) O(n^2)

Answer: c) O(log n)

4. Which sorting algorithm is used by the `Array.Sort` method in C#?

a) QuickSort

b) BubbleSort

c) MergeSort

d) InsertionSort

Answer: a) QuickSort

5. In C#, what interface must be implemented by a custom class to enable sorting


using `Array.Sort` or `List<T>.Sort`?

Disusun Oleh : Kadri Yusuf [72]


Praktik Pemrograman C#

a) ICompare

b) ISortable

c) IComparable

d) IOrdered

Answer: c) IComparable

6. Which LINQ method is commonly used for sorting a collection in ascending


order?

a) `OrderBy`

b) `SortBy`

c) `Order`

d) `Sort`

Answer: a) `OrderBy`

7. What data structure in C# allows you to quickly search for values based on
associated keys?

a) ArrayList

b) List

c) Dictionary

d) HashSet

Answer: c) Dictionary

8. Which C# collection is suitable for membership testing and searching for unique
elements with efficient lookups?

a) List<T>

b) Array<T>

c) HashSet<T>

d) Queue<T>

Answer: c) HashSet<T>

9. What is the primary advantage of using binary search over linear search in C#?

a) Binary search works with unsorted data.

Disusun Oleh : Kadri Yusuf [73]


Praktik Pemrograman C#

b) Binary search has a faster average time complexity.

c) Binary search uses fewer iterations.

d) Binary search is easier to implement.

Answer: b) Binary search has a faster average time complexity.

10. Which C# namespace provides regular expression functionality for advanced


text searching?

a) System.Text.RegularExpressions

b) System.Searching

c) System.Text.TextSearch

d) System.PatternMatching

Answer: a) System.Text.RegularExpressions

11. What is searching in C# programming?

a) Arranging elements in a specific order

b) Finding a specific element or item within a collection

c) Filtering elements from a collection

d) Counting the number of elements in a collection

Answer: b) Finding a specific element or item within a collection

12. Which searching technique involves checking each element in a collection one
by one until the target element is found?

a) Linear Search

b) Binary Search

c) Hashing

d) Quick Search

Answer: a) Linear Search

13. Binary search is efficient for searching in C# when:

a) The collection is unsorted

b) The collection is small

Disusun Oleh : Kadri Yusuf [74]


Praktik Pemrograman C#

c) The collection is sorted

d) The target element is at the beginning of the collection

Answer: c) The collection is sorted

14. Which C# method is commonly used for searching in a generic list for an
element that meets a specified condition?

a) `Find`

b) `Search`

c) `Locate`

d) `Scan`

Answer: a) `Find`

15. When working with dictionaries in C#, what type of search is most efficient for
finding values based on their associated keys?

a) Linear Search

b) Binary Search

c) Hash Table Lookup

d) Sequential Search

Answer: c) Hash Table Lookup

16. Which C# data structure is suitable for membership testing and quickly
determining whether an element exists in a collection?

a) List<T>

b) Dictionary<TKey, TValue>

c) Queue<T>

d) HashSet<T>

Answer: d) HashSet<T>

17. Regular expressions in C# are commonly used for:

a) Sorting elements in a collection

b) Searching for patterns within text

c) Converting data types

Disusun Oleh : Kadri Yusuf [75]


Praktik Pemrograman C#

d) Calculating mathematical expressions

Answer: b) Searching for patterns within text

18. In binary search, what is the time complexity for finding a target element in a
sorted collection of size 'n'?

a) O(1)

b) O(n)

c) O(log n)

d) O(n^2)

Answer: c) O(log n)

19. Which C# method is used to perform complex string matching and searching
operations using regular expressions?

a) `String.Contains`

b) `Regex.Match`

c) `String.Search`

d) `String.Match`

Answer: b) `Regex.Match`

20. In C#, which of the following is a powerful tool for searching and manipulating
text using patterns?

a) Dictionary

b) HashSet

c) Regular Expressions

d) Binary Search

Answer: c) Regular Expressions

Disusun Oleh : Kadri Yusuf [76]


Praktik Pemrograman C#

Chapter 7. Abstract & Interface

7.1 Abstract

Abstract is a keyword used to define a data type or class that cannot be


instantiated. This means you cannot create objects directly from data types or
abstract classes. The term is also used in the context of methods, which can be
"abstract methods."

The abstract keyword is used for classes and methods:

• Abstract class: is a restricted class that cannot be used to create objects (to
access it, it must be inherited from another class).
• Abstract method: can only be used in an abstract class, and it does not have a
body. The body is provided by the derived class (inherited from).

An abstract class can have both abstract and regular methods:

abstract class Animal

public abstract void animalSound();

public void sleep()

Console.WriteLine("Zzz");

From the example above, it is not possible to create an object of the Animal
class:

Animal myObj = new Animal();

Example:

// Abstract class

abstract class Animal

Disusun Oleh : Kadri Yusuf [77]


Praktik Pemrograman C#

// Abstract method (does not have a body)

public abstract void animalSound();

// Regular method

public void sleep()

Console.WriteLine("Zzz");

// Derived class (inherit from Animal)

class Cow : Animal

public override void animalSound()

// The body of animalSound() is provided here

Console.WriteLine("The Cow says: Booo");

class Program

static void Main(string[] args)

Cow myCow = new Cow(); // Create a Cow object

myCow.animalSound(); // Call the abstract method

myCow.sleep(); // Call the regular method

Disusun Oleh : Kadri Yusuf [78]


Praktik Pemrograman C#

7.2 Interface

An interface is a completely "abstract class", which can only contain abstract


methods and properties (with empty bodies):

Example:

// interface

interface Animal

void animalSound(); // interface method (does not have a body)

void run(); // interface method (does not have a body)

To access the interface methods, the interface must be "implemented" (kinda like
inherited) by another class. To implement an interface, use the : symbol (just like with
inheritance). The body of the interface method is provided by the "implement" class.
Note that you do not have to use the override keyword when implementing an
interface:

// Interface

interface IAnimal

void animalSound(); // interface method (does not have a body)

// Cow "implements" the IAnimal interface

class Cow : IAnimal

public void animalSound()

// The body of animalSound() is provided here

Console.WriteLine("The Cow says: wee wee");

Disusun Oleh : Kadri Yusuf [79]


Praktik Pemrograman C#

class Program

static void Main(string[] args)

Cow myCow = new Cow(); // Create a Cow object

myCow.animalSound();

Notes on Interfaces:

• Like abstract classes, interfaces cannot be used to create objects (in the
example above, it is not possible to create an "IAnimal" object in the Program
class)
• Interface methods do not have a body - the body is provided by the
"implement" class
• On implementation of an interface, you must override all of its methods
• Interfaces can contain properties and methods, but not fields/variables
• Interface members are by default abstract and public
• An interface cannot contain a constructor (as it cannot be used to create
objects)

Why And When To Use Interfaces?

• To achieve security - hide certain details and only show the important details
of an object (interface).
• C# does not support "multiple inheritance" (a class can only inherit from one
base class). However, it can be achieved with interfaces, because the class can
implement multiple interfaces. Note: To implement multiple interfaces,
separate them with a comma (see example below).

Disusun Oleh : Kadri Yusuf [80]


Praktik Pemrograman C#

Multiple Choice Question Chapter 7:

1. What is a primary difference between an abstract class and an interface in C#?


a. Abstract classes can have constructors; interfaces cannot.
b. Interfaces can have method implementations; abstract classes cannot.
c. Abstract classes can be instantiated; interfaces cannot.
d. Interfaces can have fields; abstract classes cannot.

Answer: c) Abstract classes can be instantiated; interfaces cannot.

2. Which keyword is used to define an abstract class in C#?


a. abstract
b. class
c. interface
d. sealed

Answer: a) abstract

3. In C#, can a class inherit from multiple abstract classes?


a. Yes
b. No

Answer: b) No

4. What is the maximum accessibility level for members of an interface in C#?


a. private
b. protected
c. internal
d. public

Answer: d) public

5. Which of the following can contain method implementations in C#?


a. Abstract class
b. Interface
c. Both abstract class and interface
d. Neither abstract class nor interface

Answer: a) Abstract class

6. Which keyword is used to declare that a class implements an interface in C#?

a. extends
b. uses
c. implements
d. inherits

Disusun Oleh : Kadri Yusuf [81]


Praktik Pemrograman C#

Answer: c) implements

7. Can an abstract class have both abstract and non-abstract methods?

a. Yes
b. No

Answer: a) Yes

8. In C#, can you define fields (variables) inside an interface?

a. Yes
b. No

Answer: b) No

9. Which of the following can have access modifiers like public, private, and
protected for their members?

a. Abstract class
b. Interface
c. Both abstract class and interface
d. Neither abstract class nor interface

Answer: a) Abstract class

10. When implementing an interface in C#, which keyword is used to explicitly


implement interface members?

a. override
b. virtual
c. interface
d. none

Answer: d) none

11. Can an abstract class have a constructor in C#?

a. Yes
b. No

Answer: a) Yes

12. What is the purpose of an abstract class in C#?

a. To provide a complete implementation for a class.


b. To define a blueprint for a class and allow some methods to be implemented
by derived classes.

Disusun Oleh : Kadri Yusuf [82]


Praktik Pemrograman C#

c. To prevent a class from being inherited.


d. To allow multiple inheritance.

Answer: b) To define a blueprint for a class and allow some methods to be


implemented by derived classes.

13. How can you achieve multiple inheritance of implementation in C#?

a. By using multiple base classes.


b. By using multiple interfaces.
c. By using both abstract classes and interfaces.
d. Multiple inheritance is not supported in C#.

Answer: b) By using multiple interfaces.

14. Which keyword is used to prevent a class from being inherited in C#?

a. sealed
b. static
c. final
d. const

Answer: a) sealed

15. What is the key difference between an interface and an abstract class in C#?

a. An abstract class can have constructors, but an interface cannot.


b. An interface can have fields, but an abstract class cannot.
c. An abstract class can provide partial implementation, but an interface
cannot.
d. An abstract class can be instantiated, but an interface cannot.
Answer: c) An abstract class can provide partial implementation, but an
interface cannot.

16. In C#, can a class implement multiple interfaces?

a. Yes
b. No

Answer: a) Yes

17. Which of the following is NOT a valid access modifier for interface members in
C#?

a. public
b. internal
c. protected

Disusun Oleh : Kadri Yusuf [83]


Praktik Pemrograman C#

d. private

Answer: c) protected

18. When a class inherits from an abstract class in C#, it must implement all of the
abstract methods unless the class itself is declared as:

a. static
b. sealed
c. abstract
d. partial

Answer: c) abstract

19. In C#, can an abstract class have non-abstract methods?

a. Yes
b. No

Answer: a) Yes

20. Which of the following statements about interfaces in C# is TRUE?

a. Interfaces can have constructors.


b. Interfaces can have instance variables.
c. Interfaces can have method implementations.
d. Interfaces can be instantiated directly.

Answer: b) Interfaces can have instance variables.

Disusun Oleh : Kadri Yusuf [84]


Praktik Pemrograman C#

Chapter 8. Graphical User Interface (GUI)

The graphical user interface (GUI) is a user interface that allows users to
interact with technology via the use of graphical icons rather than complex code. The
graphical user interface was invented in the late 1970s by the Xerox Palo Alto
research lab.

GUI was initially offered commercially for Apple's Macintosh, and Microsoft's
Windows operating systems. The model–view–controller software architecture
decouples internal data representations from the display of data to the user.

8.1 Project Creation for C# GUI in Visual Studio

You will use visual studio for this project. You will follow the following steps
to create a project:

You must click on “Create a New Project.”

Disusun Oleh : Kadri Yusuf [85]


Praktik Pemrograman C#

Then you must search “Windows Forms App (.NET Framework).”

Then you must give this project a name like “GUIDemo”


Now, you will try different features of GUI.

8.2 GUI Creation of Calculator in C#


You must change the window label from form1 to the “GUI Demo”. You can
find this in the solution explorer tab.
Now, you will check out different features of the GUI one by one

Disusun Oleh : Kadri Yusuf [86]


Praktik Pemrograman C#

Start with a button. You can find it in the Toolbox. You can name it “Click Here”. Now,
you must double-click on it to write up code to give it some functionality.
Code:

private void button1_Click(object sender, EventArgs e)


{
MessageBox.Show("Welcome To Simplilearn!!");
}

Disusun Oleh : Kadri Yusuf [87]


Praktik Pemrograman C#

Multiple Choice Question in chapter 8:


1. The reason that C# does not support multiple inheritances is because of ______.
a. Method collision
b. Name collision
c. Function collision
d. Interface collision
Answer» B. Name collision discuss
2. _______ is a set of devices through which a user communicates with a system
using interactive set of commands.
a. Console
b. System
c. Keyboard
d. Monitor
Answer» A. Console
3. Exponential formatting character (‘E’ or ‘e’) converts a given value to string in the
form of _______.
a. m.dddd
b. E+xxx
c. m.dddd
d. E+xxx
Answer» A. m.dddd
4. The ______ are the Graphical User Interface (GUI) components created for web
based interactions..
a. Web forms
b. Window Forms
c. Application Forms
d. None of the above
Answer» B. Window Forms
5. In Microsoft Visual Studio, ______ technology and a programming language such
as C# is used to create a Web based application.
a. JAVA
b. J#
c. VB.NET
d. ASP.NET
Answer» D. ASP.NET
6. The controls available in the tool box of the ______ are used to create the user
interface of a web based application.
a. Microsoft visual studio IDE

Disusun Oleh : Kadri Yusuf [88]


Praktik Pemrograman C#

b. Application window
c. Web forms
d. None of the above
Answer» A. Microsoft visual studio IDE
7. Web Forms consists of a _______ and a _________ .
a. Template, Component
b. CLR, CTS
c. HTML Forms, Web services
d. Windows, desktop
Answer» A. Template, Component
8. The ______ parentheses that follow _____ indicate that no information is passed
to Main().
a. Empty, class
b. Empty, submain
c. Empty, Main
d. Empty, Namespace
Answer» C. Empty, Main
9. The scope of a variable depends on the ____________ and _________.
a. Main method, place of its declaration
b. Type of the variable, console
c. compiler, main
d. Type of the variable, place of its declaration
Answer» B. Type of the variable, console
10. Which of the following statements is correct about the C#.NET code snippet given
below?
class Student s1, s2; // Here 'Student' is a user-defined
class. s1 = new Student();
s2 = new Student();
a. Contents of s1 and s2 will be exactly same.
b. The two objects will get created on the stack.
c. Contents of the two objects created will be exactly same.
d. The two objects will always be created in adjacent memory locations.
Answer» C. Contents of the two objects created will be exactly same.
11. Which of the following can be facilitated by the Inheritance mechanism?
1 Use the existing functionality of base class.
2 Overrride the existing functionality of base class.
3 Implement new functionality in the derived class.
4 Implement polymorphic behaviour.
5 Implement containership.

Disusun Oleh : Kadri Yusuf [89]


Praktik Pemrograman C#

a. 1, 2, 3
b. 3, 4
c. 2, 4, 5
d. 3, 5
Answer» A. 1, 2, 3
12. Which of the following should be used to implement a 'Has a' relationship
between two entities?
a. Polymorphism
b. Templates
c. Containership
d. Encapsulation
Answer» C. Containership
13. Which of the following should be used to implement a 'Like a' or a 'Kind of'
relationship between two entities?
a. Polymorphism
b. Containership
c. Templates
d. Inheritance
Answer» D. Inheritance
14. How can you prevent inheritance from a class in C#.NET ?
a. Declare the class as shadows.
b. Declare the class as overloads.
c. Declare the class as seal
Answer» C. Declare the class as seal
15. A class implements two interfaces each containing three methods. The class
contains no instance data. Which of the following correctly indicate the size of the
object created from this class?
a. 12 bytes
b. 24 bytes
c. 0 byte
d. 8 bytes
Answer» B. 24 bytes
16. Which of the following statements is correct about Interfaces used in C#.NET?
a. All interfaces are derived from an Object class.
b. Interfaces can be inherited.
c. All interfaces are derived from an Object interface.
d. Interfaces can contain only method declaration.
Answer» B. Interfaces can be inherited.
17. Which of the following statements is correct about an interface used in C#.NET?

Disusun Oleh : Kadri Yusuf [90]


Praktik Pemrograman C#

a. If a class implements an interface partially, then it should be an abstract class.


b. Class cannot implement an interface partially.
c. An interface can contain static methods.
d. An interface can contain static data.
Answer» A. If a class implements an interface partially, then it should be an
abstract class.
18. Which of the following statements is correct about an interface?
a. One interface can be implemented in another interface.
b. An interface can be implemented by multiple classes in the same program.
c. A class that implements an interface can explicitly implement members of that
interface.
d. The functions declared in an interface have a body.
Answer» C. A class that implements an interface can explicitly implement
members of that interface.
19. Databases store information in records, fields and:
a. data providers
b. grids
c. columns
d. tables
Answer» D. tables
20. Each data provider class is grouped and accessible through its:
a. namespace
b. database
c. datagrid
d. provider
Answer» A. namespace

Disusun Oleh : Kadri Yusuf [91]


Praktik Pemrograman C#

Chapter 9. Validation

Validation in C# programming is the process of verifying the correctness,


integrity, and security of data to ensure that it meets specific criteria or rules before it
is processed, stored, or used in an application. Data validation is crucial for building
robust, secure, and reliable software systems. It helps prevent errors, vulnerabilities,
and data inconsistencies. Here's an overview of validation in C# programming:

9.1 The important of Data Validation


1. Data Integrity: Validation ensures that data is accurate and consistent,
preventing corruption of databases or data stores.
2. Security: Proper data validation helps protect against security vulnerabilities,
including SQL injection, cross-site scripting (XSS), and other attacks that
exploit incorrect or malicious data.
3. User Experience: Validation provides immediate feedback to users when they
input data incorrectly, improving the user experience and reducing frustration.
4. Data Quality: Validating data at the source helps maintain data quality
throughout the application's lifecycle.
5. Compliance: Some industries and applications require strict data validation to
comply with regulatory standards, ensuring data accuracy and privacy.

9.2 Common Types of Data Validation in C#


1. Type Validation: Ensuring that data matches the expected data type (e.g.,
integers, strings, dates, custom objects).
2. Range Validation: Verifying that data falls within acceptable numerical or
value ranges (e.g., checking if an age input is within 0-120).
3. Length Validation: Checking the length of strings, arrays, or collections to
ensure they fall within specified limits.
4. Format Validation: Ensuring that data adheres to specific formats (e.g., email
addresses, phone numbers, postal codes).
5. Presence Validation: Verifying that required fields are not empty or null.
6. Uniqueness Validation: Checking that data is unique within a dataset (e.g.,
unique usernames, email addresses).

9.3 Data Validation Performance


1. Conditional Statements (if-else): Use conditional statements to check data
against specific conditions and take appropriate actions if validation fails.

Disusun Oleh : Kadri Yusuf [92]


Praktik Pemrograman C#

if (age < 0 || age > 120)


{
// Invalid age
// Handle the error
}

2. Regular Expressions (Regex): Use regular expressions to validate data against


specific patterns (e.g., email, phone number).
using System.Text.RegularExpressions;

string emailPattern = @"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-


Z]{2,}$";
if (!Regex.IsMatch(email, emailPattern))
{
// Invalid email format
// Handle the error
}

3. Data Annotations: Utilize data annotations from the


`System.ComponentModel.DataAnnotations` namespace to define validation
rules directly within model classes.
using System.ComponentModel.DataAnnotations;
public class User
{
[Required]
[EmailAddress]
public string Email { get; set; }

[Range(0, 120)]
public int Age { get; set; }
}

4. Custom Validation Methods: Implement custom validation methods that


perform specific checks.
public bool IsPhoneNumberValid(string phoneNumber)
{
// Custom validation logic
// Return true if valid, false otherwise

Disusun Oleh : Kadri Yusuf [93]


Praktik Pemrograman C#

5. Exception Handling: Throw exceptions when validation fails, and catch them
where needed. This is useful for handling errors gracefully.
if (string.IsNullOrEmpty(username))
{
throw new ArgumentException("Username cannot be empty.");
}

9.4 Using of Validation In Windows Form Application


Here are the steps:

Step 1: Create a Windows form application.

Step 2: Choose “ErrorProvider” form toolbox.

Step 3: Select the Text box and go to its properties.

Disusun Oleh : Kadri Yusuf [94]


Praktik Pemrograman C#

In properties choose “Events” and under focus double click on “validating”.

Now we have the text box validation method.

private void textBoxName_Validating(object sender, CancelEventArgs e)

if (string.IsNullOrWhiteSpace(textBoxName.Text))

e.Cancel = true;

textBoxName.Focus();

errorProviderApp.SetError(textBoxName, "Name should not be left blank!");

} else

e.Cancel = false;

errorProviderApp.SetError(textBoxName, "");

Step 4: Now validation should be triggered on Enter key press. Add following code
to Enter key click method.

private void buttonEnter_Click(object sender, EventArgs e)

if (ValidateChildren(ValidationConstraints.Enabled))

Disusun Oleh : Kadri Yusuf [95]


Praktik Pemrograman C#

MessageBox.Show(textBoxName.Text, "Demo App - Message!");

Also make sure that Enter button's "CauseValidation" property should be set to
"true".

Disusun Oleh : Kadri Yusuf [96]


Praktik Pemrograman C#

Validation Example 2:

Code :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
//import the regular expression library
using System.Text.RegularExpressions;

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

//initialize the validating method


static Regex Valid_Name = StringOnly();
static Regex Valid_Contact = NumbersOnly();
static Regex Valid_Password = ValidPassword();
static Regex Valid_Email = Email_Address();

Disusun Oleh : Kadri Yusuf [97]


Praktik Pemrograman C#

//Method for validating email address


private static Regex Email_Address()
{
string Email_Pattern = @"^(?!\.)(""([^""\r\\]|\\[""\r\\])*""|"
+ @"([-a-z0-9!#$%&'*+/=?^_`{|}~]|(?<!\.)\.)*)(?<!\.)"
+ @"@[a-z0-9][\w\.-]*[a-z0-9]\.[a-z][a-z\.]*[a-z]$";

return new Regex(Email_Pattern, RegexOptions.IgnoreCase);


}
//Method for string validation only
private static Regex StringOnly()
{
string StringAndNumber_Pattern = "^[a-zA-Z]";

return new Regex(StringAndNumber_Pattern, RegexOptions.IgnoreCase);


}
//Method for numbers validation only
private static Regex NumbersOnly()
{
string StringAndNumber_Pattern = "^[0-9]*$";

return new Regex(StringAndNumber_Pattern, RegexOptions.IgnoreCase);


}
//Method for password validation only
private static Regex ValidPassword()
{
string Password_Pattern = "(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-
9]{8,15})$";

return new Regex(Password_Pattern, RegexOptions.IgnoreCase);


}

//Validate all textboxes when the button is clicked

private void btnSave_Click_1(object sender, EventArgs e)


{
//for Name
if (Valid_Name.IsMatch(txtName.Text) != true)
{
MessageBox.Show("Namme accepts only alphabetical characters",
"Invalid", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
txtName.Focus();
return;
}

//for Address
if (txtAddress.Text == "")
{
MessageBox.Show("Address cannot be empty!", "Invalid",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
txtAddress.Focus();
return;
}
//for Contacts
if (Valid_Contact.IsMatch(txtContactNo.Text) != true)
{
MessageBox.Show("Contact accept numbers only.", "Invalid",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
txtContactNo.Focus();
return;
}
//for username

Disusun Oleh : Kadri Yusuf [98]


Praktik Pemrograman C#

if (txtUsername.Text == "")
{
MessageBox.Show("Username cannot be empty!", "Invalid",
MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
txtUsername.Focus();
return;
}
//for password
if (Valid_Password.IsMatch(txtPassword.Text) != true)
{
MessageBox.Show("Password must be atleast 8 to 15 characters. It
contains atleast one Upper case and numbers.", "Invalid", MessageBoxButtons.OK,
MessageBoxIcon.Exclamation);
txtPassword.Focus();
return;
}
//for Email Address
if (Valid_Email.IsMatch(txtEmailAddress.Text) != true)
{
MessageBox.Show("Invalid Email
Address!","Invalid",MessageBoxButtons.OK ,MessageBoxIcon.Exclamation );
txtEmailAddress.Focus();
return;
}

//success message
MessageBox.Show("You are now successfully registered.");

//hidding all object in the form


foreach(Control txt in this.Controls)
{
if (txt is Control)
{
txt.Visible = false;

}
}

}
}

Disusun Oleh : Kadri Yusuf [99]


Praktik Pemrograman C#

Multiple Choice Question in chapter 9:


1. What is the primary purpose of data validation in C# .NET Windows Forms?
a. To make your form look visually appealing
b. To prevent users from entering data
c. To ensure that user input meets predefined criteria
d. To store user input securely
Answer: c) To ensure that user input meets predefined criteria
2. Which event occurs when a control is about to lose focus and is a common place
to implement validation logic?
a. Click
b. Enter
c. Validating
d. MouseHover
Answer: c) Validating
3. In the Validating event handler, how can you prevent a control from losing focus
when validation fails?
a. Set the Validating property of the control to false.
b. Set the Cancel property of the event arguments to true.
c. Call the e.StopPropagation() method.
d. Use the e.PreventDefault() method.
Answer: b) Set the Cancel property of the event arguments to true.
4. What is the purpose of the ErrorProvider control in Windows Forms?
a. It plays sound effects when errors occur.
b. It provides detailed error reports to Microsoft.
c. It displays error icons and messages next to controls with validation errors.
d. It prevents errors from occurring in the first place.
Answer: c) It displays error icons and messages next to controls with validation
errors.
5. How can you set an error message for a control using the ErrorProvider
component?
a. Use the control.SetError(errorMessage) method.
b. Set the ErrorText property of the control to the error message.
c. Call the SetError(control, errorMessage) method of the ErrorProvider.
d. Use the ErrorMessage property of the ErrorProvider control.
Answer: c) Call the SetError(control, errorMessage) method of the ErrorProvider.
6. In a Windows Forms application, which method can be called to trigger the
Validating and Validated events for all controls on the form that require
validation?
a. ValidateChildren()

Disusun Oleh : Kadri Yusuf [100]


Praktik Pemrograman C#

b. CheckAllValidations()
c. RunValidation()
d. ValidateForm()
Answer: a) ValidateChildren()
7. When should you typically call the ValidateChildren() method in a Windows
Forms application?
a. In the Form_Load event
b. In the Form_Closing event
c. In a button click event for form submission
d. In the Validating event of each control
Answer: c) In a button click event for form submission
8. Which property is commonly used in validation logic to determine if a control's
input is valid?
a. IsValid
b. ValidationState
c. IsError
d. ValidInput
Answer: a) IsValid
9. What is SQL injection, and how is it related to validation in C# .NET forms?
a. SQL injection is a technique to inject malware into forms, and validation
prevents it.
b. SQL injection is a security vulnerability that can occur when user input is not
properly validated, allowing malicious SQL code to be executed.
c. SQL injection is a way to validate user input securely.
d. SQL injection is a database query optimization technique.
Answer: b) SQL injection is a security vulnerability that can occur when user input
is not properly validated, allowing malicious SQL code to be executed.
10. Which event occurs after the Validating event, allowing you to handle any post-
validation actions?
a. Valid
b. Validated
c. ValidationComplete
d. Verify
Answer: b) Validated
11. In Windows Forms, what is the purpose of the Validating and Validated events?
a. To perform validation logic on a control's input
b. To paint the control with different colors
c. To prevent user input
d. To refresh the form

Disusun Oleh : Kadri Yusuf [101]


Praktik Pemrograman C#

Answer: a) To perform validation logic on a control's input


12. What is the role of the Cancel property in the Validating event handler?
a. To cancel the form submission
b. To cancel the event and prevent the control from losing focus
c. To cancel the application's execution
d. To cancel the ErrorProvider display
Answer: b) To cancel the event and prevent the control from losing focus
13. In a Windows Forms application, what happens if the Validating event handler
sets e.Cancel to true?
a. The application crashes.
b. The control's input is cleared.
c. The control remains in focus, and the user can correct the input.
d. The control loses focus and the form is submitted.
Answer: c) The control remains in focus, and the user can correct the input.
14. Which component is used to provide visual feedback in the form of error icons and
messages for controls with validation errors?
a. Validator
b. ValidationErrorProvider
c. ErrorManager
d. ErrorProvider
Answer: d) ErrorProvider
15. When validating user input in a Windows Forms application, what is the primary
purpose of displaying an error message next to a control?
a. To hide the control from the user
b. To provide the user with instructions on how to fix the error
c. To lock the control to prevent further input
d. To indicate that the control is read-only
Answer: b) To provide the user with instructions on how to fix the error
16. Which method can be used to remove the error message and icon displayed by
the ErrorProvider for a specific control?
a. RemoveError()
b. ResetError()
c. ClearError()
d. SetError(control, "")
Answer: d) SetError(control, "")
17. How can you handle a situation where the user closes a Windows Form with
validation errors?
a. Display a confirmation dialog and ask the user if they want to save the
changes.

Disusun Oleh : Kadri Yusuf [102]


Praktik Pemrograman C#

b. Prevent the user from closing the form until all validation errors are resolved.
c. Automatically save the changes and close the form.
d. Show an error message and terminate the application.
Answer: b) Prevent the user from closing the form until all validation errors are
resolved.
18. Which control allows you to specify custom validation logic for a control and
display a custom error message?
a. ErrorProvider
b. Validator
c. ErrorLabel
d. ErrorProvider with custom messages
Answer: b) Validator
19. In a Windows Forms application, what does the ErrorProvider control do when
there are no validation errors?
a. It displays a green checkmark icon.
b. It hides the form's controls.
c. It remains invisible.
d. It does nothing.
Answer: d) It does nothing.
20. What is the primary purpose of using validation in a C# .NET Windows Forms
application?
a. To make the application look more colorful
b. To block all user input
c. To ensure that user input is accurate and meets specific criteria
d. To limit the number of controls on a form
Answer: c) To ensure that user input is accurate and meets specific criteria

Disusun Oleh : Kadri Yusuf [103]


Praktik Pemrograman C#

Chapter 11. GUI Component (Music


Player)
There are several ways to create a player in C# but in this article, I will describe the simplest way to
create an MP3 player that plays .mp3 and .wav files only, because I set the Filter property of the
opendialog box.

Use the following procedure to create it.

Step 1

Open Visual Studio 2010


"File" -> "New" -> "Project..."
Choose "Template" -> "Visual C#" -> "Windows Form Application "
Step 2

Now add the windows Media Player control in your Toolbox.

Right-click in toolbox
Select "Choose items"
Look for the Windows Media Player within the "COM components" tab of the Choose
toolbox Items window

Disusun Oleh : Kadri Yusuf [104]


Praktik Pemrograman C#

Note: Now the Windows Media Player control is added to your toolbox.

Step 3

Now deign the form as you need to for the control. Here I use a TableLayout panel
control on the form and set these properties to "Columncount =1, Dock =Fill and
Rows=3". Now I have inserted the Windows Media Player control from the toolbox
in the first row of the TableLayout panel and set the property "Dock=Fill". A list box
and button control in the second and third row of the table layout panel with "Dock
=Fill" property. And a OpenFileDialog to select one or more .mp3 files to play with
the property.

Disusun Oleh : Kadri Yusuf [105]


Praktik Pemrograman C#

Note: Now your windows look like this:

Step 4

Now write the following C# code in the "Form1.cs" page:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;

Disusun Oleh : Kadri Yusuf [106]


Praktik Pemrograman C#

using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace media_player
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string[] files, path;
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() ==System.Windows .Forms .DialogResult
.OK)
{
files = openFileDialog1.SafeFileNames;
path = openFileDialog1.FileNames;
for (int i = 0; i< files.Length; i++)
{
listBox1.Items.Add(files[i]);
}
}
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
axWindowsMediaPlayer1.URL = path[listBox1.SelectedIndex];
}
}
}

Step 5

Run your program.

Disusun Oleh : Kadri Yusuf [107]


Praktik Pemrograman C#

Disusun Oleh : Kadri Yusuf [108]


Praktik Pemrograman C#

Disusun Oleh : Kadri Yusuf [109]


Praktik Pemrograman C#

Chapter 12. Database

A database in a C# Windows Forms application is a structured collection of


data that is used to store, retrieve, and manage information. Databases are an
essential component of many software applications, including C# Windows Forms
applications, as they allow you to organize and manipulate data efficiently. Here's an
explanation of how databases are typically used in C# Windows Forms applications.
12.1 Data Storage
Data storage refers to the process of storing and managing data within the
application, typically to preserve and manipulate information, settings, or other
relevant data. In Windows Forms applications, data storage can take various forms
and may involve different techniques and technologies. Here's a comprehensive
explanation of data storage in C# Windows Forms applications:
12.1.1 Data Storage Option
There are several ways to store data in a C# Windows Forms application:
a. File Storage: You can store data in files on the local file system. Common file
formats for data storage include text files (e.g., CSV, XML), binary files, and
custom file formats.
b. Database Storage : As discussed in a previous response, databases are used
to store structured data. This is often the preferred option for larger volumes
of data and for data that requires structured organization and efficient
querying.
c. Memory Storage : You can store data in memory within your application. This
could include using data structures like lists, dictionaries, or custom objects to
hold and manage data while the application is running. Keep in mind that this
data is not persistent and will be lost when the application is closed.
d. Registry (Windows-specific): Windows provides a registry for storing
configuration and settings data. While this is not recommended for general
application data storage, it's sometimes used for application settings.
e. Cloud Storage: You can store data in the cloud using services like Azure
Storage, Amazon S3, or Google Cloud Storage. This is useful for data that
needs to be accessible from multiple locations or for scalability and backup
purposes.
12.1.2 File Storage
When storing data in files, you can use different file formats based on your
needs. For example:

Disusun Oleh : Kadri Yusuf [110]


Praktik Pemrograman C#

a. Text Files (CSV, XML, JSON) : These formats are human-readable and are often
used for configuration files and small to medium-sized data sets.
b. Binary Files: Binary files are more compact and efficient for certain data
structures, but they are not human-readable. You'll need to serialize and
deserialize your data when reading/writing binary files.
c. Custom File Formats: You can create your own file format for data storage if
none of the existing formats suit your requirements. This typically involves
defining the file structure and writing code to read and write data in that
format.
12.1.3 Database Storage
When using a database for data storage, you typically interact with the
database using technologies like Entity Framework, ADO.NET, or other database-
specific libraries. Key concepts include:
1. Connection : Establishing a connection to the database server to perform data
operations.
2. SQL (Structured Query Language) : Writing SQL queries to interact with the
data in the database, including SELECT, INSERT, UPDATE, DELETE, and more.
3. Data Access Layer (DAL) : Creating a DAL to abstract the database operations
and provide a clean interface for your application to interact with the database.
4. Object-Relational Mapping (ORM): Using ORM frameworks like Entity
Framework to work with databases using C# objects and classes.
12.1.4 Memory Storage
Storing data in memory is suitable for temporary data that needs to be
accessed and manipulated within the application's runtime. Data structures like Lists,
Dictionaries, and custom objects can be used for in-memory storage.
12.1.5 Persistence
When you need to preserve data beyond the application's current session, you
need to implement data persistence. This can involve saving data to files, updating a
database, or using other techniques to ensure data is retained between application
launches.

12.1.6 Security and Encryption


Data storage should consider security and encryption, especially for sensitive
information. You may need to encrypt files, secure database connections, and follow
best practices for protecting data.
12.1.7 Error Handling and Data Integrity
Robust error handling is essential to manage data storage errors gracefully.
Additionally, ensuring data integrity and consistency is crucial, especially when
dealing with databases.

Disusun Oleh : Kadri Yusuf [111]


Praktik Pemrograman C#

12.1.8 Data Binding


Data stored in your application can be bound to user interface controls in Windows
Forms to display and manipulate the data in a user-friendly way. This allows users to
interact with and edit the stored data.

12.2 Data Retrieval


C# Windows Forms applications need to retrieve data from databases. This
data can be displayed in the user interface or used for various purposes within the
application.

12.3 Data Modification


Applications often need to add, update, or delete data in the database. This
could involve creating new records, modifying existing ones, or removing records that
are no longer needed.

12.4 Structured Data


Databases use tables to structure data. Each table is made up of rows and
columns, much like a spreadsheet. The structure of a database is defined by its
schema, which specifies the tables, their columns, data types, and relationships
between tables.

12.5 Relational Databases


C# applications often work with relational databases, such as Microsoft SQL
Server, MySQL, SQLite, or Oracle. These databases use structured query language
(SQL) to interact with the data.

12.6 Database Connection


To work with a database in a C# Windows Forms application, you typically
need a database connection. You establish a connection to the database server to
perform data operations.

12.7 Data Access Layer


It's common to create a data access layer in your C# application. This layer acts
as an intermediary between your application and the database. It abstracts the
database operations and provides a clean interface for interacting with the database.

12.8 Object-Relational Mapping (ORM)

Disusun Oleh : Kadri Yusuf [112]


Praktik Pemrograman C#

ORM frameworks like Entity Framework enable you to work with databases using C#
objects and classes, rather than writing raw SQL queries. This simplifies data access
and reduces the need for manual SQL.

12.9 CRUD Operations


In C# Windows Forms applications, you often perform CRUD (Create, Read, Update,
Delete) operations on the database. For example, you can create new records, read
data from the database, update existing records, and delete records.

12.10 Data Binding


You can bind data from the database to user interface controls in your Windows
Forms application. This allows you to display and edit data in a user-friendly way.

12.11 Security and Authentication


Access to the database is typically restricted and secured. You may need to
implement authentication and authorization mechanisms to control who can access
and manipulate the data.

12.12 Error Handling and Transactions


Robust error handling and transaction management are essential for
maintaining data consistency and integrity in the database.

To work with databases in C# Windows Forms applications, you'll often use libraries,
frameworks, and APIs that provide database connectivity and query execution
capabilities. Entity Framework and ADO.NET are two commonly used approaches for
working with databases in C# applications. These tools simplify database
interactions and help you create robust and efficient data-driven applications.
Creating Database project in C#.

Step 1

Open Visual Studio. Here I am using Visual Studio 2019 and SQL Server
Management Studio 2018.

Step 2

Click on the File menu then hover on the new option. Then click on Project, or
you can use the shortcut key Ctrl + Shift +N.

Disusun Oleh : Kadri Yusuf [113]


Praktik Pemrograman C#

Step 3

Select Windows Form application and click on the Next button. If you cannot find
the Windows Form application, you can use the search box or filter dropdowns.

Disusun Oleh : Kadri Yusuf [114]


Praktik Pemrograman C#

Step 4

On the next screen, you need to enter the following details and click on the
create button.
• Project Name - Your project name which is also your solution name.
• Location - Select the file location where you want to save your
project.
• Framework - Select the .NET Framework version that you want to use.
I prefer to use the latest version.

Disusun Oleh : Kadri Yusuf [115]


Praktik Pemrograman C#

Step 5

Now your project is created. Now you can see the designer page of your form.
Create a design as per your requirement. Here I create the following simple
design for a CRUD operation.

Disusun Oleh : Kadri Yusuf [116]


Praktik Pemrograman C#

Step 6

Now open your SQL Server Management Studio and create a table as per your
requirement. Here I created a table with the following fields. If you don’t want to
use SQL Server Management Studio, you can also use Visual Studio server
explorer by adding a new database to your project.

Disusun Oleh : Kadri Yusuf [117]


Praktik Pemrograman C#

Step 7

Now your table is ready and we can create the store procedure for this CRUD
operation. Following is the store procedure code.
1. USE [Tutorials]
2. GO
3. /****** Object: StoredProcedure [dbo].[EmployeeCrudOperat
ion] Script Date: 11/14/2020 6:02:30 PM ******/
4. SET ANSI_NULLS ON
5. GO
6. SET QUOTED_IDENTIFIER ON
7. GO
8. -- =============================================
9. -- Author: <Yogeshkumar Hadiya>
10. -
- Description: <Perform crud operation on employee table>

11. -- =============================================
12. ALTER PROCEDURE [dbo].[EmployeeCrudOperation]
13. -- Add the parameters for the stored procedure here
14. @Employeeid int,
15. @EmployeeName nvarchar(50),
16. @EmployeeSalary numeric(18,2),
17. @EmployeeCity nvarchar(20),
18. @OperationType int
19. --================================================
20. --operation types
21. -- 1) Insert
22. -- 2) Update
23. -- 3) Delete
24. -- 4) Select Perticular Record
25. -- 5) Selec All
26. AS
27. BEGIN
28. -
- SET NOCOUNT ON added to prevent extra result sets from
29. -- interfering with SELECT statements.
30. SET NOCOUNT ON;
31.
32. --select operation
33. IF @OperationType=1
34. BEGIN
35. INSERT INTO Employee VALUES (@EmployeeName,@Emplo
yeeSalary,@EmployeeCity)
36. END
37. ELSE IF @OperationType=2
38. BEGIN

Disusun Oleh : Kadri Yusuf [118]


Praktik Pemrograman C#

39. UPDATE Employee SET EmployeeName=@EmployeeName ,


EmployeeSalary=@EmployeeSalary ,EmployeeCity=@EmployeeCity
WHERE EmployeeId=@Employeeid
40. END
41. ELSE IF @OperationType=3
42. BEGIN
43. DELETE FROM Employee WHERE EmployeeId=@Employeeid

44. END
45. ELSE IF @OperationType=4
46. BEGIN
47. SELECT * FROM Employee WHERE EmployeeId=@Employee
id
48. END
49. ELSE
50. BEGIN
51. SELECT * FROM Employee
52. END
53.
54. END
Code Explanation
• First of all, here I declare five following parameters which we will pass
from the C# code.

o Employee Id
Employee id will be used for select employee, delete an
employee, and update employee record

o Employee Name
Employee name will be passed in the employee name
column in the employee table

o Employee City
Employee City will be passed in employee city column in
the employee table

o Employee Salary
Employee Salary will be passed in the employee salary
column in the employee table

o Operation Type
Operation Type defines the type of operation which we
want to perform. We will user 1 for Insert, 2 For Update, 3
For Delete , 4 for select single record and 5 for select all

Disusun Oleh : Kadri Yusuf [119]


Praktik Pemrograman C#

records.

• Then we divide code by an if-else condition and perform the task as


per the operation type parameter
Step 8

Now back to Visual Studio. Open Server Explorer and click on add database
button. If you created a database in the project, then right-click on the database
name and click on modify.

Step 9

Enter the Server name, here I used the local server so I just enter local and click
on refresh. Select the database that you want to use and click on the advance
button.

Disusun Oleh : Kadri Yusuf [120]


Praktik Pemrograman C#

Step 10

Now you will see a new popup window, select connection string code. Close all
popups.

Disusun Oleh : Kadri Yusuf [121]


Praktik Pemrograman C#

Step 11

Now double-click anywhere in your form to generate a Form_Load event, or you


can generate it by going to the property window and clicking on the event icon
(thunder icon) and select Form_Load event. Replace the following code with your
event code and also import System.Data.SqlClient namespace. Here, I disable
the update and delete button on a load we will enable that buttons when the
user gets a single employee record by clicking on the find employee button.
1. SqlConnection cn;
2. SqlCommand cmd;
3. SqlDataAdapter da;
4. SqlDataReader dr;
5. private void Form1_Load(object sender, EventArgs e)
6. {
7. cn = new SqlConnection(@"Data Source=(local);Initial C
atalog=Tutorials;Integrated Security=True");
8. cn.Open();
9. //bind data in data grid view
10. GetAllEmployeeRecord();
Disusun Oleh : Kadri Yusuf [122]
Praktik Pemrograman C#

11.
12. //disable delete and update button on load
13. btnUpdate.Enabled = false;
14. btnDelete.Enabled = false;
15. }
Step 12

Now we create a method to get all data from the table and set in data grid view.
We will use this code many times, so we create a simple method for this.
Following is the code to get all records from the table and set it in data grid view.
1. private void GetAllEmployeeRecord()
2. {
3. cmd = new SqlCommand("EmployeeCrudOperation", cn);
4. cmd.CommandType = CommandType.StoredProcedure;
5. cmd.Parameters.AddWithValue("@Employeeid", 0);
6. cmd.Parameters.AddWithValue("@EmployeeName", "");
7. cmd.Parameters.AddWithValue("@EmployeeSalary", 0);
8. cmd.Parameters.AddWithValue("@EmployeeCity", "");
9. cmd.Parameters.AddWithValue("@OperationType", "5");
10. da = new SqlDataAdapter(cmd);
11. DataTable dt = new DataTable();
12. da.Fill(dt);
13. dataGridView1.DataSource = dt;
14.
15. }
Code Explanation
• First, we pass our Store Procedure name and Connection object in
the SqlCommand object which we defined at the top of the page.
• Define command type as Store Procedure
• Pass all parameters with null and zero value and pass 5 (five) which is
the Operation type to get all records from the Store procedure.
• Initialize Command object to DataAdapter object
• Create a new DataTable object and pass value from the data adapter
object to the data table object by fill method.
• Set the data table object to data grid view.
Step 13

Now generate a method for saving by double-clicking on a save button and add
the following code in the save button click event.
1. private void Btnsave_Click(object sender, EventArgs e)
2. {
3. if (txtempcity.Text != string.Empty && txtempname.Tex
t != string.Empty && txtempsalary.Text != string.Empty)
4. {
5. cmd = new SqlCommand("EmployeeCrudOperation", cn);

Disusun Oleh : Kadri Yusuf [123]


Praktik Pemrograman C#

6. cmd.CommandType = CommandType.StoredProcedure;
7. cmd.Parameters.AddWithValue("@Employeeid", 0);
8. cmd.Parameters.AddWithValue("@EmployeeName", txtem
pname.Text);
9. cmd.Parameters.AddWithValue("@EmployeeSalary", txt
empsalary.Text);
10. cmd.Parameters.AddWithValue("@EmployeeCity", txte
mpcity.Text);
11. cmd.Parameters.AddWithValue("@OperationType", "1"
);
12. cmd.ExecuteNonQuery();
13. MessageBox.Show("Record inserted successfully.",
"Record Inserted", MessageBoxButtons.OK, MessageBoxIcon.In
formation);
14. GetAllEmployeeRecord();
15. txtempcity.Text = "";
16. txtempid.Text = "";
17. txtempname.Text = "";
18. txtempsalary.Text = "";
19. }
20. else
21. {
22. MessageBox.Show("Please enter value in all fields
", "Invalid Data", MessageBoxButtons.OK, MessageBoxIcon.In
formation);
23. }
Code Explanation
• First, we check that a user entered a value in all fields if not then
show the message or else proceed.
• Then same as get all record method pass parameter in store
procedure but here we user ExecuteNonQuery method for insert into
the table.
• Then show a success message, next, a call function that we generated
to get all data from the table and clear all text boxes.
Output

Disusun Oleh : Kadri Yusuf [124]


Praktik Pemrograman C#

Step 14

Now generate a click event on find employee button to get a single employee
record by passing its id and show data in another textbox. Add the following
code in find button event.
1. private void Btnfind_Click(object sender, EventArgs e)
2. {
3. if (txtempid.Text != string.Empty)
4. {
5.
6. cmd = new SqlCommand("EmployeeCrudOperation", cn);

7. cmd.CommandType = CommandType.StoredProcedure;
8. cmd.Parameters.AddWithValue("@Employeeid", txtempi
d.Text);
9. cmd.Parameters.AddWithValue("@EmployeeName", "");

10. cmd.Parameters.AddWithValue("@EmployeeSalary", 0)
;
11. cmd.Parameters.AddWithValue("@EmployeeCity", "");

Disusun Oleh : Kadri Yusuf [125]


Praktik Pemrograman C#

12. cmd.Parameters.AddWithValue("@OperationType", "4"


);
13. dr = cmd.ExecuteReader();
14. if (dr.Read())
15. {
16. txtempname.Text = dr["EmployeeName"].ToString
();
17. txtempsalary.Text = dr["EmployeeSalary"].ToSt
ring();
18. txtempcity.Text = dr["EmployeeCity"].ToString
();
19. btnUpdate.Enabled = true;
20. btnDelete.Enabled = true;
21. }
22. else
23. {
24. MessageBox.Show("No record found with this id
", "No Data Found", MessageBoxButtons.OK, MessageBoxIcon.I
nformation);
25. }
26. dr.Close();
27. }
28. else
29. {
30. MessageBox.Show("Please enter employee id ", "Err
or", MessageBoxButtons.OK, MessageBoxIcon.Error);
31. }
32. }
Code Explanation
• First of all, check that the user entered an employee ID
• Then pass the employee ID and operation type parameter. All other
parameters are null or zero
• Then we call the ExecuteReader method of SQL Command and
initialize data into SQL Data Reader object
• Then we check if the data reader has data by the read() method
• If the data reader has data then put that data in textbox and enable
delete and update buttons, otherwise show a message that the
employee ID was not found
• In the last close data reader object.
Output

Disusun Oleh : Kadri Yusuf [126]


Praktik Pemrograman C#

Step 15

Now generate a click event on the update button by double-clicking on that and
replace it with the following code. The code is the same as the insert code, but
here we also check whether the employee ID is available or not.
1. private void BtnUpdate_Click(object sender, EventArgs e)
2. {
3. if (txtempcity.Text != string.Empty && txtempid.Text !
= string.Empty && txtempname.Text != string.Empty && txtem
psalary.Text != string.Empty)
4. {
5. cmd = new SqlCommand("EmployeeCrudOperation", cn);

6. cmd.CommandType = CommandType.StoredProcedure;
7. cmd.Parameters.AddWithValue("@Employeeid", txtempi
d.Text);
8. cmd.Parameters.AddWithValue("@EmployeeName", txtem
pname.Text);
9. cmd.Parameters.AddWithValue("@EmployeeSalary", txt
empsalary.Text);

Disusun Oleh : Kadri Yusuf [127]


Praktik Pemrograman C#

10. cmd.Parameters.AddWithValue("@EmployeeCity", txte


mpcity.Text);
11. cmd.Parameters.AddWithValue("@OperationType", "2"
);
12. cmd.ExecuteNonQuery();
13. MessageBox.Show("Record update successfully.", "R
ecord Updated", MessageBoxButtons.OK, MessageBoxIcon.Infor
mation);
14. GetAllEmployeeRecord();
15. btnDelete.Enabled = false;
16. btnUpdate.Enabled = false;
17. }
18. else
19. {
20. MessageBox.Show("Please enter value in all fields
", "Invalid Data", MessageBoxButtons.OK, MessageBoxIcon.In
formation);
21. }
22. }
Output

Disusun Oleh : Kadri Yusuf [128]


Praktik Pemrograman C#

Step 16

Now generate a click event on the delete button and replace the following code
with that.
1. private void BtnDelete_Click(object sender, EventArgs e)
2. {
3. if (txtempid.Text != string.Empty)
4. {
5. DialogResult dialogResult = MessageBox.Show("Are y
ou sure you want to delete this employee ? ", "Delete Empl
oyee", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk);

6. if (dialogResult == DialogResult.Yes)
7. {
8.
9. cmd = new SqlCommand("EmployeeCrudOperation",
cn);
10. cmd.CommandType = CommandType.StoredProcedure
;
11. cmd.Parameters.AddWithValue("@Employeeid", tx
tempid.Text);
12. cmd.Parameters.AddWithValue("@EmployeeName",
"");
13. cmd.Parameters.AddWithValue("@EmployeeSalary"
, 0);
14. cmd.Parameters.AddWithValue("@EmployeeCity",
"");
15. cmd.Parameters.AddWithValue("@OperationType",
"3");
16. cmd.ExecuteNonQuery();
17. MessageBox.Show("Record deleted successfully.
", "Record Deleted", MessageBoxButtons.OK, MessageBoxIcon.
Information);
18. GetAllEmployeeRecord();
19. txtempcity.Text = "";
20. txtempid.Text = "";
21. txtempname.Text = "";
22. txtempsalary.Text = "";
23. btnDelete.Enabled = false;
24. btnUpdate.Enabled = false;
25. }
26. }
27. else
28. {
29. MessageBox.Show("Please enter employee id", "Inva
lid Data", MessageBoxButtons.OK, MessageBoxIcon.Informatio
n);

Disusun Oleh : Kadri Yusuf [129]


Praktik Pemrograman C#

30. }
31. }
Output

Conclusion
In this article, we performed a CRUD operation with a store procedure. If you
have any questions or suggestions about this article, you can comment them
below, and if you found this article helpful, please share it with your friends.

Disusun Oleh : Kadri Yusuf [130]


Praktik Pemrograman C#

References:

1. If Statement in JavaScript (tutorjoes.in)


2. https://www.w3schools.com/
3. chatgpt
4. https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-
types/collections
5. https://www.simplilearn.com/tutorials/c-sharp-tutorial/c-sharp-gui
6. https://mcqmate.com/topic/956/c-programming-set-5
7. https://www.knowledgehut.com/tutorials/csharp/csharp-hashset-collection
8. 500+ C# Programs - Sanfoundry
9. SQL Server Database Connection In C# Using ADO.NET (c-sharpcorner.com)
10. https://www.c-sharpcorner.com/blogs/how-to-use-validation-in-windows-
form-application

Disusun Oleh : Kadri Yusuf [131]

You might also like