0% found this document useful (0 votes)
47 views82 pages

Manul - Lab - Event - Driven Programming

This document discusses C# programming concepts including switch-case statements, if-else statements, loops, LINQ, and event-driven programming. It provides code examples and explanations of various C# topics to help beginners learn the fundamentals of C#.

Uploaded by

Efrata Teriesa
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)
47 views82 pages

Manul - Lab - Event - Driven Programming

This document discusses C# programming concepts including switch-case statements, if-else statements, loops, LINQ, and event-driven programming. It provides code examples and explanations of various C# topics to help beginners learn the fundamentals of C#.

Uploaded by

Efrata Teriesa
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/ 82

Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

Content of course

1.1 Syntax of switch...case statement.................................................................................................3


1.2 Rules for working with switch case ..............................................................................................4
1.3 Flowchart of switch...case statement............................................................................................6
1.4 Example program of switch...case statement ...............................................................................6
1.5 Nesting of switch...case statement................................................................................................8
1.5.1 Syntax of nested switch...case statement..............................................................................8 2
C# if else ...............................................................................................................................................8 3
Switch ...................................................................................................................................................9 4
While loop...........................................................................................................................................10 5
............................................................................................................................................................10 6
Do-While loop ....................................................................................................................................10
6.1 How do...while loop works?.......................................................................................................11 6.1.1
Explanation of the above program......................................................................................12 7 Foreach
loop .......................................................................................................................................12 7.1
syntax:.........................................................................................................................................12 8
Continue statement............................................................................................................................13 9
Break ...................................................................................................................................................13 10
Function ..........................................................................................................................................14 10.1
C# cal by value ............................................................................................................................14 10.2 C#
call by reference ....................................................................................................................14 10.3 C# out
parameter .......................................................................................................................14 10.4 Create a
Method .....................................................................................................................14 10.4.1 LINQ
TUTORIAL ..............................................................................................................14 11 LINQ
Introduction .........................................................................................................................15 11.1.1
WHAT IS LINQ? ...............................................................................................................15 11.1.2 WHY
WE NEED LINQ?...................................................................................................16 11.1.3 THE
ADVANTAGE OF USING LINQ............................................................................17 12 Linq Syntax
And Query – How To Write Linq Syntax.................................................................18 12.1.1 QUERY
SYNTAX .............................................................................................................18 12.1.2
PROGRAMMING EXAMPLE 1 ......................................................................................18 1. Firstly,
create database by name called Billing _System then create table by tbl_assement ..............50
1
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

2. Business logic layers...........................................................................................................................50


3. Data layer............................................................................................................................................50
4. UI(PRESENTATION LAYERS.........................................................................................................58
4.1. Double click on add then write code as follows .............................................................................59
4.2. Double click on update then write code as follows.........................................................................61
4.3. Double click on delete then write code as follows..........................................................................62
4.4. Double click on view then write code as follows ...........................................................................63
4.5. Firstly create DGVPrinter.cs under DAL then then copy 3883 line of code under it then .............63
4.6. Double click on print then write code as follows but .....................................................................63
Table of content of event driven lab lab 9
..................................................................................................98

............99 1. Business logic


.....................................................................................................................................99 2. Data
layer..........................................................................................................................................100 3. UI
......................................................................................................................................................106 3.1.
double click on update and write the following code in it ...........................................................107 3.2.
double click on delete and write the following code in it .............................................................108 3.3.
Write the method as follows before clear button ..........................................................................109 3.4.
double click on generate report and write the following code in it...............................................110 3.5.
double click on update button .......................................................................................................110 3.6.
double click on view button then write following in it .................................................................111

2
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane
C# (pronounced C Sharp) is new technology that is much effectfulness and easy to learn. It
consists of thousands of prebuilt classes and interfaces that lets programmer to write powerful
code in very less time. as beginners try to evining into then don’t worry and just start with very
first lesson and do exercises regularly.

I promise you to in very short time you will be able to write complex programming module
without getting help of any third party resources. To run C# code, Visual Studio is the best editor.
Either you can choose console based application to run program directly or you can write
program on notepad and then run them on visual studio command prompt. This online C#
programming guide will help you to be a C# expert in next few days

if...else statement provides support to control program flow. if statement make decisions based on
conditions. It selects an action, if some condition is met. However, there exits situations where
you want to make a decision from available choices. For example – select a laptop from
available models, select a menu from available menu list etc.

switch...case statement gives ability to make decisions from fixed available choices. Rather
making decision based on conditions. Using switch we can write a more clean and optimal code,
that take decisions from available choices.

1.1 Syntax of switch...case statement

switch(expression){

case 1:

/* Statement/s */
break;
case 2:
/* Statement/s */
break;
case n:
/* Statement/s */
3
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

break;
default:
/* Statement/s */
}

1.2 Rules for working with switch case

• Expression inside switch must evaluate to integer, character or enumeration constant.


switch...case only works with integral, character or enumeration constant.

• The case keyword must follow one constant of type evaluated by expression. The case
along with a constant value is known as switch label.

• You can have any number of cases.

• Each and every case must be distinct from other. For example, it is illegal to write two case
1 label.

• You are free to put cases in any order. However, it is recommended to put them in
ascending order. It increases program readability.

• You can have any number of statement for a specific case.

• The break statement is optional. It transfers program flow outside of switch...case. break
statement is covered separately in this C tutorial series.

• The default case is optional. It works like an else block. If no cases are matched then the
control is transferred to default block.Working of switch...case statement

Let me take an example to demonstrate the working of switch...case statement.

Classification of programming languages

int num = 2;

switch(num){
case 1: Console.write("I am One"); break;

4
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

case 2: Console.write("I am Two"); break;

case 3: Console.write("I am Three"); break;

default: Console.write("I am an integer. But, definitely I am not 1, 2 and 3."); }

• Initially I declared an integer variable num = 2.

• switch(num) will evaluate the value of num to 2.

• After switch(num) got evaluated, switch knows the case to transfer program control.

• Instead of checking all cases one by one. It transfers program control directly to case 2. If
value of num is not matched with any case then switch transfers control to default case, if
defined.

• After the control has been set to case 2. It executes all statements inside the case. The case
contains two statement first Console.write("I am Two"); and second break.
Console.write("I am Two"); will print “I am Two” on console and transfers control to
break.

• break statement terminates switch...case and transfer program control to statement after
switch.

What if I don’t use break keyword? If you don’t use break keyword, it executes all below
cases until break statement is found. It doesn’t matter whether the remaining case matches
or not, it will execute all below case from matching case in the absence of break keyword.
5
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

1.3 Flowchart of switch...case statement

1.4 Example program of switch...case statement

Let us write a C program to input week number from user and print the corresponding day name of week.
// C# program to print day of week name
Using System;
Public static void main(){
/* Declare integer variable to store week number */
int week;
/* Input week number from user */
Console.write("Enter week number (1-7): ");
Week=Int.Parse(Console.ReadLine());
switch(week) {

6
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

case 1: /* If week == 1 */
Console.write("Its Monday.\n");
Console.write("Its a busy day."); break; case 2: /* If
week == 2 */
Console.write("Its Tuesday."); break;
case 3: /* If week == 3 */
Console.write("Its Wednesday."); break; case 4: /* If
week == 4 */
Console.write("Its Thursday.\n");
Console.write("Feeling bit relaxed."); break; case 5:
Console.write("Its Friday."); break;
case 6: /* If week == 6 */
Console.write("Its Saturday.\n");
Console.write("It is weekend."); break; case 7: /* If
week == 7 */
Console.write("Its Sunday.\n");
Console.write("Hurray! Its holiday.");
break;
default: /* If week < 1 or week > 7 */
Console.write("Um! Please enter week number between 1-7."); }
}
Output –

Enter week number (1-7): 6

Its Saturday.

It is weekend.

7
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

1.5 Nesting of switch...case statement

C# supports nesting of one switch...case inside other. However, it is not recommended model to
put one switch...case inside other. As nesting of switch decreases code readability.

1.5.1 Syntax of nested switch...case statement

switch(expression){

case 1: /* Statement/s */

break;
case 2: /* Statement/s */
switch(inner_expression) {
case 1:
/* Statement/s */
break;
case 2: /* Statement/s */
break;
case n: /* Statement/s */
break;
default: /* Statement/s */
break;
}
break;
case n: /* Statement/s */
break;
default: /* Default statement/s */
}

2 C# if else
In csharpe programming the if statement is used to test the condition.

8
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

There are various types of if statements in C#.


➢ If statement
➢ If- else statement
➢ Neste-if stament
➢ If-else -if ladder
If statement tests the condition. It is executed if condition is fired
Syntax
If(condition){
There is code should be written
}

3 Switch
Switch statement executes one statement from multiple condition given. It is like if-else-if
ladder statement
Switch(expression){
Case value1://code to be executed Break;
Case value2://code to be executed Break;
}
Default://code to be executed if all cases are not matched; Break;
For loop
The c# for loop is used to iterate a part of the program several times.if the number
of iteration is fixed, it is recommended to use for loop than while or do-while loops

9
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

4 While loop
In csharp while loop is used to iterate a part of the program several times.if the number of
iteration is not fixed,it is recommended to use while loop than for loop
5
6 Do-While loop
In csharp do-while loop is used to iterate a part of the program several times.if the number of
iteration is not fixed and you must have to execute the loop at leaset once,it is recommended to
use do-while loop than for loop because of do-while loop checked after loop body

10
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

do...while is an exit controlled looping statement. We use do...while loop when


there is a need to check condition after execution of loop body. do...while loop in
any case executes minimum once

6.1 How do...while loop works?

do...while loop works in two step.

1. Initially program control transfers to body of loop. It executes all statements inside loop
body and transfers control to loop condition.

2. Loop condition contains set of relational and logical expressions. If conditional expression
evaluates 1 (true) then loop repeats again otherwise if conditional expression evaluates 0
(false) loop terminates
Class program {

Public static void Main(Strings[] arg){

/* Loop counter variable declaration */


int n=1;
do {
/* Body of loop */
Console.write( n);
/* Update loop counter variable */
n++;

} while(n <= 10); /* Loop condition */

}}

Output –

11
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

1 2 3 4 5 6 7 8 9 10

6.1.1 Explanation of the above program

• The statement int n=1; declares an integer loop counter variable initialized with 1.
• Next program control directly enters in loop body and executes the statement
Console.write("%d ", n);. It print current value of n i.e. 1 for first run.

• The statement n++; increments the value of n by 1.

• Finally, loop condition part receives program control. Inside loop condition it evaluates (n
<= 10). If the statement is true then the loop will continue otherwise terminate. For now it
checks with n=1 i.e. while(1 <= 10); which is true hence loop continues.

• In next iteration it prints 2 and increment n again by 1. Finally checks the loop condition
while(n <= 10); which is again true

7 Foreach loop
foreach loop is a different kind of looping constructs in C# programming that doesn’t includes
initialization, termination and increment/decrement characteristics. It uses collection to take value
one by one and then processes them.

7.1 syntax:

1. console.write(“enter value”);
2. int n=Int.parse(console.ReadLine());

12
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

3. foreach (string name in n)


4. {
5. Console.Write(name);
6. }

Where, name is a string variable that takes value from collection as arr and then processes them
in the body area.

8 Continue statement
The c# continue statement is used to continue loop it continues the current follow of program and skips
the remaining code at specified condition.in case of inner loop, it continues only inner loop

Using System

Public static void Main(String [],arg){


For(int i=1;i<=10;i++){

If(i==6)

Continue;

}Console.Write(i)}}

9 Break
The csharp is used to break loop or switch statement. It breakthe current flow of the program at the
given condition. In case of inner loop, it breaks only breaks only inner loop

Public static void Main(String [],arg){

For(int i=1;i<=10;i++){

If(i==6)

Continue;

}Console.Write(i)}}

13
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

10 Function
10.1 C# cal by value
10.2 C# call by reference
10.3 C# out parameter

A method is a block of code which only runs when it is called. You can pass data, known as
parameters, into a method. Methods are used to perform certain actions, and they are also known
as functions. Why use methods? To reuse code: define the code once, and use
it many times.

10.4 Create a Method


A method is defined with the name of the method, followed by parentheses (). C# provides some
pre-defined methods, which you already are familiar with, such as Main(), but you can also create
your own methods to perform certain actions:

Create a method inside the Program class:

class Program

static void MyMethod()

// code to be executed

10.4.1 LINQ TUTORIAL

• LINQ (C#)
• Introduction
• LINQ Query Syntax
• LINQ Method Syntax
• LINQ - List Example
• Lambda Expression and Delegates
• Basic Operators
o Where

14
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

o Select & SelectMany


o OrderBy & OrderByDescending
o ThenBy & ThenByDescending
o Reverse
o GroupBy
o ToLookup
o LINQ Methods
o All() and Any() Method
o Range, Repeat and Empty
• LINQ with ArrayList
• LINQ with Dictionary
• LINQ with SQL Database

11 LINQ Introduction
In this chapter, you will learn

1. What is LINQ?

2. Why we need LINQ?

3. Advantage of LINQ

11.1.1 WHAT IS LINQ?

LINQ is a short form of Language Integrated Query and it is mainly used for querying data
(save and retrieve data) from a different data source like SQL Database, XML Documents,
ADO.Net Dataset and .NET Collections etc. LINQ is a programming language which was first
introduced in Visual Studio 2008 with .NET 3.5. C# and VB both support LINQ Syntax and in
this tutorial, we will learn how to write LINQ query for accessing and managing data.

15
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane
11.1.2 WHY WE NEED LINQ?

This is the very basic question which comes in our mind that Why we need LINQ if we have
SQL for querying relational database and XQuery for querying XML? When each data source
has their specific query language then why need to develop an extra programming language?

A new technology is getting developed continuously and the developer has had to learn a
different language each time. So, it was the demand of the time that there must be a unique and
common query language that works with all types of data source. LINQ fulfill this requirement
very well. Now, you don’t need to learn different types of query language to work with different
types of data source. Just learn LINQ and work with any types of data source.

16
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

11.1.3 THE ADVANTAGE OF USING LINQ

1. Common Query - LINQ provides common query across various kinds of data source SQL Database,
ADO.NET Dataset, XML Documents, .NET Collection etc.

2. Working with Objects - In LINQ, you will always work with objects so you can use the same basic

pattern of coding with different types of data source.

3. Less Coding - LINQ reduces the number of coding lines. Dozens of lines of codes can be written in

LINQ in a single line.

4. Easy to Understand – LINQ is an easy to understand and more readable code. So other developers

can easily understand LINQ query.

5. Compile Time Safety – It checks codes on compile time so it reduces the risk of Runtime Error. 6.

IntelliSense Support - LINQ provides IntelliSense support that makes programming more confident.

17
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

12 Linq Syntax And Query – How To Write Linq

Syntax In this tutorial, you will learn:

1. Linq Syntax and Query

2. How to write Linq Query

3. Query Syntax and Method Syntax

There are 2 types of LINQ Syntax, which you need to learn:

1. Query Syntax

2. Method Syntax

12.1.1 QUERY SYNTAX

Query Syntax is easy to learn. It has SQL like query syntax but it does not support all query
operators in LINQ. Method Syntax is the more powerful way to write LINQ queries and it is also
a standard way to write LINQ syntax.

Define

1. From <range variable> in <IEnumerable<T> or IQueryable<t>


collection> 2. <standard query operators> <lambda expression>
3. <select or groupBy operator> <result formation>

Note: LINQ query always returns a list of items.

12.1.2 PROGRAMMING EXAMPLE 1

In this example, I am going to create a simple product list and then access all the items using the
LINQ query. This is a simple console example.

1. using System;
18
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

2. using System.Collections.Generic;
3. using System.Linq;
4.
5. namespace LinqExample
6. {
7. class Program
8. {
9. static void Main(string[] args)
10. {
11. // Creating List
12. IList<string> productList = new List<string>() 13. {
14. "Hard Disk",
15. "Monitor",
16. "SSD Disk",
17. "RAM",
18. "Processor",
19. "Bluetooth",
20. "Keyboard & Mouse"
21. };
22.
23. var result = from s in productList 24. select s;
25.
26. foreach(string str in result)
27. {
28. Console.WriteLine(str.ToString()); 29. }

1. Write menu based program

using System;
using System.Collections.Generic;
using System.Linq;

19
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane
using System.Text;
using System.Threading.Tasks;
namespace switch_do_while_for
{
class Program
{
public static object Continue { get; private set; }
public static object Int { get; private set; }

static void Main(string[] args)


{
int i = 0, j = 0, sum = 0, op;
do{
Console.WriteLine("1 your option forloop");
Console.WriteLine("2 your option whle loop");
Console.WriteLine("3 your option do--while");
Console.WriteLine("4.enter your volume of sphere please");
Console.WriteLine("5 enter your circumference of circle please");
Console.WriteLine("6.program to display area of triangle sides");
Console.WriteLine("7.program to display sum of n natural number");
Console.WriteLine("8.program to display in km input in meter");
Console.WriteLine("9.program to convert decimal to octal number");
Console.WriteLine("10.program to convert binary to decimal number");
Console.WriteLine("11.program to display 1 to 100 odd number in decreasing order");
Console.WriteLine("12.program to display fib series");
Console.WriteLine("13.program to display foreach loop");
Console.WriteLine("14.program to display foreach loop");
Console.WriteLine("15.program to display foreach loop");
Console.WriteLine("16.program to display distance measurement");
Console.WriteLine("17.program to display weight measurement");
Console.WriteLine("press 90 to exit the program ");
op = int.Parse(Console.ReadLine());
switch (op) {
case 1: Console.WriteLine("you select for loop operation man!");
for (i = 1; i < 10; i++){
sum = sum + i;
Console.WriteLine(" sum of " + i +"th"+ " round " + sum);
}
break;
case 2:
Console.WriteLine("you select while loop operation man!");
while (i < 10)
{
sum = sum + i;
Console.WriteLine(" sum of " + i + " round" + sum);
i++;
}
break;
case 3:
Console.WriteLine("you select do while loop operation man!");
do
{
sum = sum + i;
Console.WriteLine(" i am from do--while sum of " + i+"th" + " round " + sum);
i++;
} while (i < 10);
break;
case 4:

20
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

float vol,r;
Console.WriteLine("enter the radius of sphere:");
r = float.Parse(Console.ReadLine());
vol = (4.0f / 3.0f) * 3.14F * r * r * r;
Console.WriteLine("The volume of sphere is :"+vol);
break;

case 5:
float cir, r1;
Console.WriteLine("enter the radius of sphere:");
r1 = float.Parse(Console.ReadLine());
cir = 2 * 3.14f *r1 ;
Console.WriteLine("The circuference of cirle is :" + cir);
break;
case 6:
float a,b,c,s, area;
Console.WriteLine("enter the three side of traingle :");
a = float.Parse(Console.ReadLine());
b = float.Parse(Console.ReadLine());
c = float.Parse(Console.ReadLine());
s = (a + b + c) / 2;
area = (float)Math.Sqrt(s * (s - a)*(s - b)*(s - c));
Console.WriteLine("The area of traingle is :"+area);
break;
case 7:
int n, sum1=0 ;
Console.WriteLine("enter the value of n :");
n = int.Parse(Console.ReadLine());
sum1 = n*(n+1)*(2*n+1)/6;
Console.WriteLine("the sum of square of first "+n+"natural number is :" + sum1);
break;
case 8:
float m,km,meter;
Console.WriteLine("enter the distance in meter :");
m = float.Parse(Console.ReadLine());
km = m/1000;
meter = m % 1000;
Console.WriteLine("The distance in kilometer is :" + km);
Console.WriteLine("The distance in meters is :" + meter);
break;
case 9:
int n1, octal = 0, rem, i1 = 1;
Console.WriteLine("enter the decimal number :");
n1= int.Parse(Console.ReadLine());
while (n1 != 0) {
rem = n1 % 8;
n1 = n1 / 8;
octal += rem * i1;
i1 *= 10; }
Console.WriteLine("octal numbe is :" + octal);
break;
case 10:
int n2, dec= 0, rem1, i2 = 1;
Console.WriteLine("enter the binary number :");
n2 = int.Parse(Console.ReadLine());
while (n2!= 0)
{ rem = n2 % 10;
dec += rem * i2;
21
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

i2 *= 2;
n2 = n2 / 10;

}
Console.WriteLine("decimal numbe is :" + dec);

break;

case 11:
int p;
Console.WriteLine("enter the maximum number you need to display in decreasing order it
depands on your input :");
p = int.Parse(Console.ReadLine());
for(p=p;p>0;p-=2)
{
Console.WriteLine("decimal numbe is :" + p);

}
break;
case 12:
int m1 = 0, m2 = 1, m3;
Console.WriteLine("enter the value max you need to display number :");
int pq = int.Parse(Console.ReadLine());
Console.Write(m1 + " " + m2);
for (int h = 1; h < pq; h++)
{
m3 = m1 + m2;
m1 = m2;
m2 = m3;

Console.Write("\t" + m3);
}

break;

case 13:
Console.Write("enter value");
string [] k = { "mamo","abebe"} ;
foreach (string name in k)
{
Console.Write(""+name+" ");
}
break;
case 14: // Creating List
IList<string> productList = new List<string>()
{
"mamo abebe", "aster mengistu", " muse mamo ", "abigya mamo","korcho
mengistu","tedalech mengistu","abebe & bedane"
};

var result = from s1 in productList


select s1;

foreach (string str in result)


{
Console.WriteLine(str.ToString());

22
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

}
break;
case 15:Console.WriteLine("display about continue statemen");
int aa;
for (aa=1;aa<=10;aa++)
{
if (aa==6)
continue;
Console.Write(i);
}
break;
case 16:Console.WriteLine(" enter milligram ,gram to convertion milligram ");
float kk = float.Parse(Console.ReadLine());
float gram = kk / 1000;
Console.WriteLine("convertion from milligram to gram="+gram);
break;
case 17:
Console.WriteLine(" enter decimeter ,decigram to convertion gram ");
float v = float.Parse(Console.ReadLine());
float gram1 = v / 10;
Console.WriteLine("convertion from milligram to gram=" + gram1);
break;
default: Console.WriteLine("invalid input"); break;
}
} while (op != 0);
Console.Read();
}
}
}

23
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

2. }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace grade
{
class Program
{
static void Main(string[] args) {
int mk=0;

do {
try

24
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane
{
Console.WriteLine("enter your mark\n"); mk =
int.Parse(Console.ReadLine()); switch (mk/10) {
case 1:
case 2:
case 3:
Console.WriteLine("F"); break; case 4:
Console.WriteLine("D"); break; case 5:
Console.WriteLine("C"); break; case
6:Console.WriteLine("C+"); break; case
7:Console.WriteLine("B"); break; case 8:
Console.WriteLine("A-"); break; case
9:Console.WriteLine("A"); break; case
10:Console.WriteLine("A+"); break; default:
Console.WriteLine("invalid"); break; }
}catch (Exception ex)
{
Console.Write(ex); }

} while (mk!=999);
Console.Read();
}

private static void exit(int v)


{
throw new NotImplementedException(); } }}

25
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FR{
class Program {
static void Main(string[] args)
{
int i, sum = 0;
do {
Console.WriteLine("enter your option");
int n = int.Parse(Console.ReadLine());

if (n == 1)
{
for (i = 1; i < 5; i++)
{
sum = sum + i;
Console.WriteLine("the sum of " + i + " round " + sum);

26
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

}
}

else if (n == 2) {
i = 1;
while (i < 5) {
sum = sum + i;
Console.WriteLine("the sum of " + i + " round " + sum); i++;
}
}
} while (true);
Console.Read();
} }}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace name_100{
class Program {
static void Main(string[] args) {
int i;
for (i = 0; i < 100; i++)
Console.WriteLine(i+" muse");
Console.Read();

}}}

27
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

public static void Main(string[]


args) {for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
Console.Write(j); }
Console.WriteLine();
}
Console.ReadKey(); }

public static void Main(string[]


args) {for (int i = 5; i>= 1; i--)

28
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane
{
for (int j = 5; j >= 1; j--)
{
Console.Write(j);
}
Console.WriteLine();

}
Console.ReadKey();
}

1) Write the output pattern


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace a1
{
class Program
{
public static void Main(string[] args)
{
int n = 5;
int k = 1;
for (int i = 1; i < n; i++)
{ for (int j = 1; j <= n; j++)
{
Console.Write("{0,4:D}",k);
29
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

k++;
}
Console.WriteLine();

}
Console.ReadKey();

}
}

2) Write the program which print this pattern

public static void Main(string[] args) {


int n = 5;
int k = 1;
for (int i = 1; i < n; i++)
{ for (int j = 1; j <= n; j++) {
Console.Write("{0,4:D}",k); k+=2;
}
Console.WriteLine();

}
Console.ReadKey();
30
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane
} }}

3) Write the program that print this pattern


public static void Main(string[] args)
{ int n = 5;
int k = 2;
for (int i = 1; i < n; i++)
{ for (int j = 1; j <= n; j++)
{
Console.Write("{0,4:D}",k); k+=2;
}
Console.WriteLine();

}
Console.ReadKey();

4) Write the program that print this pattern


class Program
{
public static void Main(string[] args)
{int n = 5;
for (int i = 1; i < n; i++)
{ for (int j = 1; j <= n; j++)

31
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane
{ Console.Write("{0,4:D}",(i*j));
}
Console.WriteLine();

}
Console.ReadKey();

}}

5) Write program that display this pattern


class Program
{
public static void Main(string[] args) {
int n = 5;
for (int i = 1; i <= n; i++) { for (int j = 1;
j <= n; j++)
{
Console.Write("{0,3:D}",(j+""+i+""));
}
Console.WriteLine();

}
Console.ReadKey();

}}

32
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane
Practical about controlling loop
choice number you need 2
Enter number of rows (for diamond dimension)
:7 1

123

12345

1234567

123456789

1234567891011

12345678910111213

1234567891011

123456789

1234567

12345

123

choice number you need 3


Enter the number of rows :6
*
***
*****
*******
*********
***********

33
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

choice number you need 6


Enter the number of rows
:7

***

*****

*******

*********

***********

*************

choice number you need 3


Enter the number of rows
:7 *
***
*****
*******
*********
***********
*************

choice number you need 4


Enter the number of
rows:6 * *

34
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

****

******

********

**********

************

choice number you need 5


Enter the number of rows
:7 *

****

******

********

**********

***************

* * * * * * * * * * * choice
number you need 8

35
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

******

*****

****

***

**

**

***

****

*****

choice number you need 9


A
BC
DEF
GHIJ
KLMNO
PQRSTU
VWXYZ[\
]^_`abcd
efghijklm
nopqrstuvw

36
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

xyz{|}~•???
????????????
choice number you need 10
A
BB
CCC
DDDD
EEEEE
FFFFFF
GGGGGGG
HHHHHHHH
IIIIIIIII
JJJJJJJJJJ
KKKKKKKKKKK
LLLLLLLLLLLL
MMMMMMMMMMMMM
NNNNNNNNNNNNNN
OOOOOOOOOOOOOOO
PPPPPPPPPPPPPPPP
QQQQQQQQQQQQQQQQQ
RRRRRRRRRRRRRRRRRR
SSSSSSSSSSSSSSSSSSS
TTTTTTTTTTTTTTTTTTTT
UUUUUUUUUUUUUUUUUUUUU
VVVVVVVVVVVVVVVVVVVVVV
WWWWWWWWWWWWWWWWWWWWWW
WXXXXXXXXXXXXXXXXXXXXXXXXYYYY
YYYYYYYYYYYYYYYYYYYYYZZZZZZZZZ
Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z Z choice number you need 6
Enter the number of rows :8

37
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

***

*****

*******

*********

***********

*************

***************

choice number you need 7 Enter the number of rows :7


*
***
*****
*******
*********
***********
*************
**

****
******

********

38
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

**********

************

**************

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace diamond
{
class Program
{
int n, k, c,i,j, space;
static void Main(string[] args)
{
/* C# Program - Print Diamond Pattern */

int n, c, k, space = 1, d;
do
{
Console.Write("choice number you need \t");
d = int.Parse(Console.ReadLine());
if (d == 1)
{
Console.WriteLine("Enter number of rows (for diamond dimension) : ");

39
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

n = int.Parse(Console.ReadLine()); space = n
- 1;
for (k = 1; k <= n; k++)
{
for (c = 1; c <= space; c++) {
Console.Write(" ");
}
space--;
for (c = 1; c <= (2 * k - 1); c++) {
Console.Write("*");
}
Console.WriteLine("\n"); }
space = 1;
for (k = 1; k <= (n - 1); k++) {
for (c = 1; c <= space; c++) {
Console.Write(" ");
}
space++;
for (c = 1; c <= (2 * (n - k) - 1); c++)

Console.Write("*");

Console.WriteLine("\n"); }
}
40
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

if (d == 2)
{
Console.WriteLine("Enter number of rows (for diamond dimension) : ");
Console.WriteLine();
n = int.Parse(Console.ReadLine());
space = n - 1;
for (k = 1; k <= n; k++)
{
for (c = 1; c <= space; c++)
{
Console.Write(" ");
}
space--;
for (c = 1; c <= (2 * k - 1); c++)
{
Console.Write(c);
}
Console.WriteLine("\n");
}
space = 1;
for (k = 1; k <= (n - 1); k++)
{
for (c = 1; c <= space; c++)
{
Console.Write(" ");
}
space++;
for (c = 1; c <= (2 * (n - k) - 1); c++)
Console.Write(c);

41
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

Console.WriteLine("\n");
}
}

if (d == 3)
{
int i, space1, rows, k1 = 0;
Console.Write("Enter the number of rows : ");
Console.WriteLine();
rows = int.Parse(Console.ReadLine()); for (i = 1;
i <= rows; i++)
{
for (space1 = 1; space1 <= (rows - i); space1++)
Console.Write(" ");

while (k1 != (2 * i - 1))


{
Console.Write("* ");
k1++;
}
k1 = 0;
Console.Write("\n");

}
}
if (d == 4)
{
int i, space1, rows, k1 = 0;

42
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

Console.Write("Enter the number of rows : ");


Console.WriteLine();
rows = int.Parse(Console.ReadLine()); for (i = 1;
i <= rows; i++)
{
for (space1 = 1; space1 <= (rows - i); space1++)
Console.Write(" ");

while (k1 != (2 * i))


{
Console.Write("* ");
k1++;
}
k1 = 0;
Console.WriteLine("\n");

}
}

if (d == 5)
{
int i, space1, rows, k1 = 1;
Console.Write("Enter the number of rows : ");
Console.WriteLine();
rows = int.Parse(Console.ReadLine()); for (i = 1;
i <= rows; i++)
{
for (space1 = 1; space1 <= (rows - i); space1++)
Console.Write(" ");

while (k1 != (2 * i))

43
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

{
Console.Write("* ");
k1++;
}
k1 = 0;
Console.WriteLine("\n");

}
}

if (d == 6)
{
Console.Write("Enter the number of rows : ");
Console.WriteLine();
n = int.Parse(Console.ReadLine()); int r, j, k2
= 1;
for (r = 0; r < n; r++)
{
for (j = 0; j < k2; j++)
{
Console.Write("* ");
}
k2 = k2 + 2;
Console.WriteLine("\n");
}
}

if (d ==7)
{
int p, space1, r1, k1 = 0;

44
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

Console.Write("Enter the number of rows : ");


Console.WriteLine();
r1 = int.Parse(Console.ReadLine()); for (p = 1;
p <= r1; p++)
{
for (space1 = 1; space1 <= (r1 - p); space1++)
Console.Write(" ");

while (k1 != (2 * p - 1))


{
Console.Write("* ");
k1++;
}
k1 = 0;
Console.Write("\n");

int i, sp, k7 = 0;

for (i = 1; i <= r1; i++)


{
for (sp = 1; sp <= (r1- i); sp++)
Console.Write(" ");

while (k7 != (2 * i))


{
Console.Write("* ");
k7++;

45
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

}
k7 = 0;
Console.WriteLine("\n");

}
}
if (d == 8)
{
int i, j, k8 = 8;

//
for (i = 5; i > 0; i--) {
for (j = 0; j < k8; j++) {
Console.Write(" "); }
k8 = k8 - 1;
for (j = 0; j <= i; j++) {
Console.Write("* "); }
Console.WriteLine("\n"); }

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


for (j = 0; j < k8; j++) {
Console.Write(" "); }

46
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

k8 = k8-1 ;
for (j = 0; j <= i; j++) {
Console.Write("* "); }
Console.WriteLine("\n"); }
}

// doing on alphabical if (d ==
9)
{ char ch = 'A';
for (int i = 0; i <=11; i++) {
for (int j = 0; j <= i; j++) {
Console.Write(ch+" "); ch++;
}
Console.WriteLine(); }
}
if (d ==10)
{
char ch = 'A';
for (int i =0; i <26; i++) {
for (int j = 0; j <=i; j++) {
Console.Write(ch +" ");

47
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

}
ch++;
Console.WriteLine();
}
}

} while (d!=99);

Console.ReadKey();
}

}
}

At this lab_8 session students must understand every line of code


Table of content for lab_8 lectures series by C# code

48
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

1. Firstly, create table by tbl_assement...................................................................................... 50

2. Business logic layers ............................................................................................................. 50


3. Data layer............................................................................................................................... 50

4. UI(PRESENTATION LAYERS ........................................................................................... 58

4.1. Double click on add then write code as follows................................................................ 59

4.2. Double click on update then write code as follows ........................................................... 61

4.3. Double click on delete then write code as follows ............................................................ 62

4.4. Double click on view then write code as follows.............................................................. 63

4.5. Firstly create DGVPrinter.cs under DAL then then copy 3883 line of code under it then 63

4.6. Double click on print then write code as follows but........................................................ 63

4
9
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

1. Firstly, create database by name called Billing _System then create table by tbl_assement

2. Business logic layers


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Billing_System.BLL
{
class assementBLL
{
public int id { get; set; }
public String fname { get; set; }
public String lname { get; set; }
public String section { get; set; }
public String dep { get; set; }
public String batch { get; set; }
public String course { get; set; }
public decimal q1 { get; set; }
public decimal test_one { get; set; }
public decimal mid { get; set; }
public decimal project { get; set; }
public decimal final { get; set; }
public string grade { get; set; }
}}

3. Data layer
using Billing_System.BLL;
using System;

50
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Billing_System.DAL
{
class assementDAL
{
static string myconnstring =
ConfigurationManager.ConnectionStrings["connstring"].ConnectionString;//using
System.configuration click
#region Select Data from Database
public DataTable Select()
{ //static method to connect db
SqlConnection conn = new SqlConnection(myconnstring);
DataTable dt = new DataTable();//to hold the data from db
try
{ //sql query to get data from db
String sql = "select * from tbl_assement";
SqlCommand cmd = new SqlCommand(sql, conn);//for executing command
SqlDataAdapter da = new SqlDataAdapter(cmd);//getting data from db
conn.Open();//db connection open
da.Fill(dt); //fill data in our datatable
}
catch (Exception ex)
{

51
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

MessageBox.Show(ex.Message);//throw message if any error occurs }


finally
{
conn.Close();//closing connection
}
return dt;//return the value in datatable

#endregion
#region Insert Data in Database
public bool Insert(assementBLL a)
{
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstring);
try
{
string sql = "insert into tbl_assement
(fname,lname,section,dep,batch,course,q1,test_one,mid,project,final,grade) VALUES
(@first_name,@last_name,@section,@dep,@batch,@course,@q1,@test_one,@mid,@project,
@final,@grade)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@first_name", a.fname);
cmd.Parameters.AddWithValue("@last_name", a.lname);
cmd.Parameters.AddWithValue("@section", a.section);
cmd.Parameters.AddWithValue("@dep", a.dep);
cmd.Parameters.AddWithValue("@batch", a.batch);
cmd.Parameters.AddWithValue("@course", a.course);
cmd.Parameters.AddWithValue("@q1", a.q1);
cmd.Parameters.AddWithValue("@test_one", a.test_one);

52
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

cmd.Parameters.AddWithValue("@mid", a.mid);
cmd.Parameters.AddWithValue("@project", a.project);
cmd.Parameters.AddWithValue("@final", a.final);
cmd.Parameters.AddWithValue("@grade", a.grade);
conn.Open();
int rows = cmd.ExecuteNonQuery();
//if query is executed successfully then the values to rows will be greater than 0 else it will be less
than 0
if (rows > 0)
{
// Queryable sucessfull
isSuccess = true;
}
else
{ //query failed
isSuccess = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);

}
finally
{
conn.Close();
}
return isSuccess;
}
#endregion
#region Update data in Database

53
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

public bool Update(assementBLL a)


{
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstring);
try
{
string sql = "UPDATE tbl_assement SET
fname=@first_name,lname=@last_name,section=@section,dep=@dep,batch=@batch,course=@
course,q1=@q1,test_one=@test_one,mid=@mid,project=@project,final=@final where id=@id";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@first_name", a.fname);
cmd.Parameters.AddWithValue("@last_name", a.lname);
cmd.Parameters.AddWithValue("@section", a.section);
cmd.Parameters.AddWithValue("@dep", a.dep);
cmd.Parameters.AddWithValue("@batch", a.batch);
cmd.Parameters.AddWithValue("@course", a.course);
cmd.Parameters.AddWithValue("@q1", a.q1);
cmd.Parameters.AddWithValue("@test_one", a.test_one);
cmd.Parameters.AddWithValue("@mid", a.mid);
cmd.Parameters.AddWithValue("@project", a.project);
cmd.Parameters.AddWithValue("@final", a.final);
cmd.Parameters.AddWithValue("@id", a.id);
conn.Open();
int rows = cmd.ExecuteNonQuery();
//if query is executed successfully then the values to rows will be greater than 0 else it will be
less than 0
if (rows > 0)
{
// Queryable sucessfull
isSuccess = true;
}

54
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane
else
{ //query failed
isSuccess = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);

}
finally
{
conn.Close();
}
return isSuccess;
}
#endregion
#region Delete Data from Database

public bool Delete(assementBLL a)


{
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstring); try
{
string sql = "DELETE FROM tbl_assement where id=@id";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@id", a.id); conn.Open();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)

55
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane
{
//query successfull
isSuccess = true;

}
else
{//query fail
isSuccess = false;

}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
conn.Close();
}
return isSuccess;
}
#endregion
#region Search User on Database usingKeywords
public DataTable Search(String keywords)
{ //static method to connect db
SqlConnection conn = new SqlConnection(myconnstring);
DataTable dt = new DataTable();//to hold the data from db temporare try
{ //sql query to get data from db
String sql = "select * from tbl_assement WHERE id LIKE '%" + keywords + "%'OR fname
LIKE '%" + keywords + "%' OR lname LIKE '%" + keywords + "%' OR section LIKE '%"

56
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane
+ keywords + "%' OR dep LIKE '%" + keywords + "%' or batch LIKE '%" + keywords + "%' or
course LIKE '%" + keywords + "%'";
SqlCommand cmd = new SqlCommand(sql, conn);//for executing command
SqlDataAdapter da = new SqlDataAdapter(cmd);//getting data from db
conn.Open();//db connection open
da.Fill(dt); //fill data in our datatable

}
catch (Exception ex)
{
MessageBox.Show(ex.Message);//throw message if any error occurs }

finally
{
conn.Close();//closing connection
}
return dt;//return the value in datatable
}

#endregion

}
}

57
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane
4. UI(PRESENTATION LAYERS
Donot forget to create object from both

public frmassement()
{
InitializeComponent();

}
at this place write this one
assementBLL u = new assementBLL();
assementDAL dal = new assementDAL();

58
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

4.1. Double click on add then write code as follows


//getting data from ui
try
{//getting username of the logged in user string
loggedUser = frmLogin.loggedIn; u.fname =
txtfname.Text;
u.lname = txtlname.Text;
u.section = txtsection.Text;
u.dep = txtdep.Text;
u.batch = txtbatch.Text;
u.course = txtcourse.Text;
59
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

u.q1 =decimal.Parse(txtq.Text);
u.test_one = decimal.Parse(txttest.Text);
u.mid = decimal.Parse(txtmid.Text);
u.project= decimal.Parse(txtproject.Text);
u.final = decimal.Parse(txtfinal.Text);
decimal x = (u.q1 + u.test_one + u.mid + u.project + u.final); if (x >
100)
u.grade = "error";
else if (x > 92)
u.grade = "A+";
else if (x > 85)
u.grade = "A";
else if (x > 80)
u.grade = "A-";
else if (x > 75)
u.grade = "B+";
else if (x > 70)
u.grade = "B";
else if (x > 65)
u.grade = "B-";
else if (x > 60)
u.grade = "C+";
else if (x > 45)
u.grade = "C";
else if (x > 40)
u.grade = "D";
else if (x > 36)
u.grade = "Fx";
else u.grade = "F";
//assementBLL usr = dal.GetIDFromUsername(loggedUser);
//u.added_by = usr.id;

60
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

//inserting data into database


bool success = dal.Insert(u);
//if the data is successfully inserted then the value of success will be true else it will be
false if (success == true)
{
MessageBox.Show("user successfully inserted.");
}
else
{
MessageBox.Show("Failed to add assement ");
}

DataTable dt = dal.Select(); //you can use datagridview or other place


dgvUsers.DataSource = dt;

}
catch (Exception ex) { MessageBox.Show(ex.Message);
}

4.2. Double click on update then write code as follows


try {
//get the values from user ui
u.id = Convert.ToInt32(txtassementid.Text);
u.fname = txtfname.Text;
u.lname = txtlname.Text;
u.section = txtsection.Text;
u.dep = txtdep.Text;
u.batch = txtdep.Text;
u.course = txtcourse.Text;
u.q1 = decimal.Parse(txtq.Text);
u.test_one = decimal.Parse(txttest.Text);
u.mid = decimal.Parse(txtmid.Text);
61
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

u.project = decimal.Parse(txtproject.Text);
u.final = decimal.Parse(txtfinal.Text);

//updating data into database


bool success = dal.Update(u);
//if data is updated successfully then the value of success will be true else it will be false if
(success= true)
{ //data updated successfully
MessageBox.Show("the user successfully update the data ");
}
else
{ //failed to update user data
MessageBox.Show("the user failed to update the data ");
}
//refreshing data grid view
//DataTable dt = dal.Select();
//dgvUsers.DataSource = dt;

}
catch (Exception me) { MessageBox.Show(me.Message); }

4.3. Double click on delete then write code as follows


//getting user id from form
u.id = Convert.ToInt32(txtassementid.Text);
bool success = dal.Delete(u);
//if data is deleted then the value of success will be true else it will be false
if (success == true)
{ //user deleted successfully
MessageBox.Show("user enabed to delete data successfully from database");
}
else
62
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

{ //failed to delete user


MessageBox.Show("Failed to delete");
}
//refresh data grid view
DataTable dt = dal.Select();
dgvUsers.DataSource = dt;

4.4. Double click on view then write code as follows


DataTable dt = dal.Select();
dgvUsers.DataSource = dt;

Double click on clear you can leave it or do it

4.5. Firstly create DGVPrinter.cs under DAL then then copy 3883 line of code under it then

4.6. Double click on print then write code as follows but


DGVPrinter printer = new DGVPrinter();
printer.Title = "\r\n\r\n ambo universtity department of informatin technology 3th \r\n\r\n";
printer.SubTitle = "Informatin Technology department C# lecturer by mamo \r\n phone:09-
10302229 \r\n\r\n";
printer.SubTitleFormatFlags = StringFormatFlags.LineLimit | StringFormatFlags.NoClip;
printer.PageNumbers = true;
printer.PageNumberInHeader = false;
printer.PorportionalColumns = true;
printer.HeaderCellAlignment = StringAlignment.Near;
//printer.Footer = "Discount:" + txtDiscount.Text + "%\r\n" + "VAT:" + txtVAT.Text + "%\r\n" +
"Grand Total: " + txtGrandTotal.Text + "%\r\n\r\n" + "Thank you for do bussiness with us";
printer.FooterSpacing = 15;
printer.PrintDataGridView(dgvUsers);

end of lab_8

63
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

Right click on database then click on add new database then naming your database as you

want
64
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane
this is your database name

65
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

Here is place you


write your attribute as want
66
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane
67

Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

Go to solution explorer then under your project name Rick click on reference
>click on Add Reference
Write config make tick as follows then ok
68
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

Write <connectionString > <add name= ”connstring” connectionString= ” copy to here ”


</connectionString>
69
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane
Double click on it and write two of line of

code frmuser a=new frmuser ();

a.show();

using Billing_System.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;

70
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Billing_System
{
public partial class frmAdminDashboard : Form
{
public frmAdminDashboard()
{
InitializeComponent();
}

private void userToolStripMenuItem_Click(object sender, EventArgs e) {


frmUsers a = new frmUsers();

a.Show();
}
private void frmAdminDashboard_Load(object sender, EventArgs e) {
ab.Text = frmLogin.loggedIn;//tell us logged username on to admindashboard }

private void categoToolStripMenuItem_Click(object sender, EventArgs e) {


frmCategories c = new frmCategories();

71
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

c.Show();
}

private void sessementToolStripMenuItem_Click(object sender, EventArgs e) {

}
}
}
72
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

Second step as follows


73
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

When click this popup to form


// got UI create by name frmlogin and write(copy) the following code in it

74
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

using Billing_System.BLL;
using Billing_System.DAL;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Billing_System.UI
{
public partial class frmLogin : Form
{
public frmLogin()
{
InitializeComponent();
}

LoginBLL l = new LoginBLL();


LoginDAL dal = new LoginDAL();
public static string loggedIn;

private void pictureBox1_Click(object sender, EventArgs e) {


Application.Exit();
}

75
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

private void btnlogin_Click(object sender, EventArgs e) {


l.username = txtusername.Text.Trim();
l.password = txtpassword.Text.Trim();
l.user_type = cmbusertype.Text.Trim();
//checking the login credentials
bool success = dal.LoginCheck(l);
if (success == true) {//login successull
MessageBox.Show("login is successful.");
loggedIn = l.username;
//need to open respective forms based on user type switch
(l.user_type) {
case "admin": {
//display admin dashboard
frmAdminDashboard admin = new frmAdminDashboard(); admin.Show();
this.Hide();
} break;
case "user": { //display admin dashboard
frmUserDashboad us = new frmUserDashboad(); us.Show();
this.Hide();
} break;
default ://display an error message
MessageBox.Show("invalid your type"); break; }

}
else { MessageBox.Show("login is failed.try again"); } }

76
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

private void frmLogin_FormClosing(object sender, FormClosingEventArgs e) {


frmLogin cl = new frmLogin();
cl.Show();
this.Hide();
}
}
}

// got BLL CREATE CLASS name loginBLL and write the following code in it

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Billing_System.BLL
{
class LoginBLL
{
public string username { get; set; }
public string password { get; set; }
public string user_type { get; set; }
}
}

// got DAL create by name called loginDAL and write(copy) the following code in

it using Billing_System.BLL;

77
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;

namespace Billing_System.DAL{
class LoginDAL { //static string to connect database
static string myconnstring =
ConfigurationManager.ConnectionStrings["connstring"].ConnectionString; public bool
LoginCheck(LoginBLL l) { //create a bool variable and set its value to false and return it
bool isSuccess = false;
//connecting to db

SqlConnection conn = new SqlConnection(myconnstring);


try {//sql query to check login
string sql = "select * from tbl_users where username=@username and password=@password and
user_type=@user_type";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("@username", l.username);
cmd.Parameters.AddWithValue("@password", l.password);
cmd.Parameters.AddWithValue("@user_type", l.user_type);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0) { //login sucessful

78
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

isSuccess = true;
}else { //login Check failed
isSuccess = false;
}
} catch(Exception ex) { MessageBox.Show(ex.Message); } finally {
conn.Close();
}return isSuccess;

}
}
}
using Billing_System.BLL;
using Billing_System.DAL;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;

79
Ambo university technology deparement of Information Technology prepared by Mamo abebe bedane

using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Billing_System.UI{
public partial class frmUsers : Form {

public frmUsers()
{
InitializeComponent();

}
userBLL u = new userBLL();
userDAL dal = new userDAL();

private void pictureBoxClose_Click(object sender, EventArgs e) {


this.Close();
}

private void btnadd_Click(object sender, EventArgs e) {


//getting data from ui
try
{//getting username of the logged in user
string loggedUser = frmLogin.loggedIn;
u.first_name = txtFname.Text;
u.last_name = txtLname.Text;
u.email = txtEmail.Text;
u.username = txtusername.Text;
u.password = txtPassword.Text;

80

You might also like