C# Module
C# Module
Chapter 1. C# Introduction
1.1 What is C#?
C# is used for:
• Mobile applications
• Desktop applications
• Web applications
• Web services
• Web sites
• Games
• VR
• Database applications
• And much, much more!
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.
Choose "Console App (.NET Core)" from the list and click on the Next button:
Enter a name for your project, and click on the Create button:
Visual Studio will automatically generate some code for your project:
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.
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!".
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:
Multiple Choice :
a) IBM
b) Microsoft
c) Apple
d) Google
Answer: b) Microsoft
a) System-level programming
b) Scientific computing
c) Web development
d) Game development
a) Type safety
b) Dynamic typing
c) Object-oriented
d) Managed code
b) .NET Core
c) Visual Studio
d) .NET Framework
a) C# 2.0
b) C# 3.0
c) C# 5.0
d) C# 7.0
Answer: c) C# 5.0
a) Eclipse
b) IntelliJ IDEA
c) Visual Studio
d) NetBeans
a) .NET Framework
b) .NET Standard
c) .NET Core
d) .NET Extended
a) Desktop applications
b) Web applications
c) Mobile applications
d) Cloud services
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
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
a) IoT applications
c) Game development
d) Cloud services
a) Import a namespace
b) Define a class
c) Declare a variable
d) Include a comment
Question 15: What is the primary mechanism for code execution and management
in C#?
c) Interpretation
d) Assembly language
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
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
Answer: c) To define a contract for methods that implementing classes must adhere
to
a) new
b) this
c) class
d) object
Answer: a) new
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:
Numbers
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.
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":
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:
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:
Operators
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:
Arithmetic Operators
Assignment Operators
In the example below, we use the assignment operator (=) to assign the value 10 to
a variable called x:
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.
In the following example, we use the greater than operator (>) to find out if 5 is
greater than 3:
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
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
c) 32,767
d) 2,147,483,647
Answer: d) 2,147,483,647
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#?
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
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#?
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
Chapter 3. IF Condition
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.
using System;
namespace IfConditionExample
{
class Program
{
static void Main(string[] args)
{
int number = 10;
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
{
Console.WriteLine("z is not greater than 5");
}
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.
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
}
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.
Answer: c) if
Answer: a) True
Answer: b) ||
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
Answer: b) `switch`
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
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
}
```
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
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 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 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.
References:
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:
}
while (count < 5);
In this example, the code block will be executed at least once, even if `count` is
initially not less than 5.
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.
a) `for`
b) `do-while`
c) `foreach`
d) `while`
Answer: d) `while`
a) `for`
b) `do-while`
c) `foreach`
d) `while`
Answer: b) `do-while`
a) To count iterations
Question 5: In a `for` loop, which statement is typically used to modify the loop
control variable?
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`
c) It is never checked
Question 9: In a `for` loop, where is the loop control variable usually declared?
b) To skip the rest of the current iteration and continue with the next
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`
c) It is never checked
Question 13: What is the primary purpose of a loop counter variable in a `for` loop?
b) To define a variable
Question 14: In a `while` loop, what is the first thing that happens during each
iteration?
d) To declare variables
Question 16: In a `do-while` loop, under what conditions will the loop continue to
execute?
Question 18: In a `for` loop, what is the order in which the loop statements are
executed?
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#?
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;
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,
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 */
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
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.
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
numbers[0] = 1;
numbers[1] = 2;
numbers[2] = 3;
numbers[3] = 4;
numbers[4] = 5;
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.
numbers.Add(1);
numbers.Add(2);
// ...
Example:
using System.Collections.Generic;
using System;
class Program
numbers.Add(10);
numbers.Add(20);
numbers.Add(30);
// Remove an element
numbers.Remove(20);
Console.WriteLine("List of Numbers:");
Console.WriteLine(num);
Console.ReadLine();
ageMap["Alice"] = 30;
ageMap["Bob"] = 25;
// ...
Example:
class Program
studentGrades["Alice"] = 90;
studentGrades["Bob"] = 85;
studentGrades["Charlie"] = 78;
Console.WriteLine("Student Grades:");
Console.WriteLine($"{kvp.Key}: {kvp.Value}");
Console.ReadLine();
5.2.4 HashSet<T>
uniqueNumbers.Add(1);
uniqueNumbers.Add(2);
// ...
Example:
class Program
uniqueNames.Add("Alice");
uniqueNames.Add("Bob");
uniqueNames.Add("Charlie");
// Remove an element
Console.WriteLine("Unique Names:");
Console.WriteLine(name);
Console.ReadLine();
5.2.5 Queue
taskQueue.Enqueue("Task 1");
taskQueue.Enqueue("Task 2");
// ...
Example:
class Program
messages.Enqueue("Message 1");
messages.Enqueue("Message 2");
messages.Enqueue("Message 3");
Console.WriteLine("Messages in Queue:");
Console.WriteLine(message);
Console.ReadLine();
5.2.6 Stack
historyStack.Push("Page 1");
historyStack.Push("Page 2");
// ...
Example:
using System;
using System.Collections.Generic;
class Program
myStack.Push(1);
myStack.Push(2);
myStack.Push(3);
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.
mixedList.Add(1);
mixedList.Add("Hello");
// ...
Example:
using System;
using System.Collections;
class Program
myArrayList.Add(1);
myArrayList.Add("Hello");
myArrayList.Add(3.14);
Console.WriteLine(item);
myArrayList.Remove("Hello");
5.2.8 LinkedList<T>:
linkedList.AddLast(1);
linkedList.AddLast(2);
// ...
Example:
using System;
using System.Collections.Generic;
class Program
myLinkedList.AddLast(1);
myLinkedList.AddLast(2);
myLinkedList.AddLast(3);
Console.WriteLine(item);
myLinkedList.Remove(2);
myLinkedList.AddBefore(node, 4);
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.
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) 0
6. How do you access the element at index 3 in an array named `myArray` in 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: 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
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>
d. HashSet<T>
Answer: b) List<T>
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>
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.
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: 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
6.1 Sorting
int[] numbers = { 5, 2, 9, 1, 5 };
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.
List<string> names = new List<string> { " David ", "Bob", "Charlie", " Alice" };
Again, for custom classes, you can implement the `IComparable` interface to enable
sorting using `List<T>.Sort`.
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
numbers.Sort();
Console.WriteLine();
// Using the Sort method with a custom comparison to sort in descending order
Console.WriteLine();
};
6.2 Searching
int[] numbers = { 5, 2, 9, 1, 7 };
int target = 9;
if (numbers[i] == target)
break;
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;
if (sortedNumbers[mid] == target)
break;
left = mid + 1;
else
right = mid - 1;
When working with lists or collections, you can use LINQ methods for
searching. The `Find` and `FindAll` methods are commonly used for this purpose.
6.2.4 Dictionary
{ "Alice", 30 },
{ "Bob", 25 },
{ "Charlie", 35 }
};
if (ageMap.ContainsKey(target))
// Use age
6.2.5 HashSet
if (namesSet.Contains(target))
using System.Text.RegularExpressions;
string text = "The quick brown fox jumped over the lazy dog.";
Exercise 6:
a) Array.Order
b) Array.Sort
c) Array.Swap
d) Array.Find
Answer: b) Array.Sort
a) O(1)
b) O(n)
c) O(log n)
d) O(n^2)
Answer: c) O(log n)
a) QuickSort
b) BubbleSort
c) MergeSort
d) InsertionSort
Answer: a) QuickSort
a) ICompare
b) ISortable
c) IComparable
d) IOrdered
Answer: c) IComparable
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) System.Text.RegularExpressions
b) System.Searching
c) System.Text.TextSearch
d) System.PatternMatching
Answer: a) System.Text.RegularExpressions
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
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
d) Sequential Search
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>
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
7.1 Abstract
• 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).
Console.WriteLine("Zzz");
From the example above, it is not possible to create an object of the Animal
class:
Example:
// Abstract class
// Regular method
Console.WriteLine("Zzz");
class Program
7.2 Interface
Example:
// interface
interface Animal
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
class Program
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)
• 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).
Answer: a) abstract
Answer: b) No
Answer: d) public
a. extends
b. uses
c. implements
d. inherits
Answer: c) implements
a. Yes
b. No
Answer: a) Yes
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
a. override
b. virtual
c. interface
d. none
Answer: d) none
a. Yes
b. No
Answer: a) Yes
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. 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
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
a. Yes
b. No
Answer: a) Yes
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.
You will use visual studio for this project. You will follow the following steps
to create a project:
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:
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.
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?
Chapter 9. Validation
[Range(0, 120)]
public int Age { get; set; }
}
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.");
}
if (string.IsNullOrWhiteSpace(textBoxName.Text))
e.Cancel = true;
textBoxName.Focus();
} 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.
if (ValidateChildren(ValidationConstraints.Enabled))
Also make sure that Enter button's "CauseValidation" property should be set to
"true".
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();
}
//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
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.");
}
}
}
}
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
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
Step 1
Right-click in toolbox
Select "Choose items"
Look for the Windows Media Player within the "COM components" tab of the Choose
toolbox Items window
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.
Step 4
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;
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
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.
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.
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.
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.
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.
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.
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.
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
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
records.
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.
Step 10
Now you will see a new popup window, select connection string code. Close all
popups.
Step 11
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);
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
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", "");
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);
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);
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.
References: