Introduction to C#
Computer language are divided into two types
Structured programming language
Are those programming language which have a specific structure
for programming is called structure programming language
It means:
It has predefined structure.
VB.6
Object Oriented programming language(OOP)
We create classes in this language and the objects of this class in
other projects or languages or anywhere else in current projects
What is object?
Object is the instance of a class is called object.
Anything in this world is called object.
Or object is a real world entity
Or anything in this world is called object
Or anything which have state, property and behavior is called
object.
Like ahmad is an object
Its behavior is setting, sleep, died…
1
WRITTEN BY: TASAL
Note: property are variables
Like name, height, father Name
Behavior
Speak, talk…
What is class?
Collection of object is called class.
Or
Class is the definition of an object.
Like
Human class, animal class
Note: object can be remove but class cannot be remove.
Like
Human can be died but human class cannot be finished
Note: Object oriented can provide reusability facilities for code
Note: C language is structural programming language.
And C++ is semi object oriented programming language and
Java is fully object oriented programming language
2
WRITTEN BY: TASAL
C# introduction.
C# is case sensitive language.
C# is introduced by Microsoft company.
C# is a pure object oriented programming language
Or C# is mixture of java and c++
Or C# is C type language like same with C, C++.
Note: syntax of C# is same with C++.
C# implementation
IDE (integrated development Environment)
لپاره ضرورت وی هغه ټول په یوlanguage څه چی د یو:Integrated Mean
کی ځای پر ځای شوی ویenvironment
Visual studio
Application are divided into two types
1_ console application: works on command, cmd, switch,router,
2_Windows Form application
Note: software is the collection of instruction
Namespace
3
WRITTEN BY: TASAL
Is the collection of classes is called namespaces like system this
?.system namespace have random class, string class etc
Note: For every class main method is important.
C# Structure
Using system// this is built-in name
Namespace test// user define namespace
Class program{
Static void Main(string[] args)
This is main method this is important for every class.
Output function
Console.Writeline(“this is my first program”); Or
Console.Write(“this is my first program”); Or
System.Console.Writeline(“this is my first program”);
Console.Readkey(); this is used to show output up to press any key.
Note: here system is namespace console is class and writeline is a method
Note: all built-in keyword is uppercase. Readkey();
4
WRITTEN BY: TASAL
Variable declaration in C#.
Int a;
Int b=20;
Console.Writeline(b);
Sizeof();
It is used to show data type size.
Console.write(sizeof(int));
Concatenation in C#.
Int a;
a=sizeof(int);
Console.writeline(“Size of int is:”+a);
Console.writeline(“Size of int is {0}”,a); // its called indexing method
Example
Int dari=90;
Int Pashto=99;
Int English=100;
Console.writeline(“the mark of dari is {0} \n the mark of Pashto is {1} \n the mark of English is {2}”, dari,Pashto,English);
څخه اخلیstring types دvalue هره#C :نوټ
کړوconvert کیږی نوددی لپاره دا باید موږstore کی نهint پهstring او
5
WRITTEN BY: TASAL
موږ په دوه قسمه کولای شوconversion او
int.parse:۱
convert.toInt32:۲
Input method
Console.Readline();
Example
Int Pashto;
Int dari;
Console.writeline(“Enter Pashto Marks”);
Pashto=int.parse(console.readline());
Or
Dari=convert.toInt32(console.Readline());
Clear function
This function Is used to clear processed console.
Like
Console.clear();
Casting
To convert a datatype into another datatype is called casting.
6
WRITTEN BY: TASAL
Casting can be done with two ways.
o Implicit casting
o Explicit casting
Implicit casting: is a casting which can be done by compiler
Like
Float a=3.4f;
Double b;
b=a;
Explicit casting: is a casting which can be done by the user.
Like
Int a;
Console.writeline(“enter first value”);
a=int.parse(console.readline());
goto command
this command is used to go to a specific area.
Like
ab:
Int Pashto;
Int dari;
Console.writeline(“Enter Pashto Marks”);
Pashto=int.parse(console.readline());
Console.readkey();
Goto ab;
7
WRITTEN BY: TASAL
Try and catch classes
It is used for exception handling
Example
Int a,b,result;
Console.writeline(“enter values”);
a=int.parse(console.readkey());
b=convert.toInt32(console.readkey());
try{
result=console.writeline(a/b);
Catch(exception){
Console.writeline(“Sorry num can not be divide by 0);
Basic content of each programming language.
1- Syntax
2- Namespace
3- Input method
4- Output method
5- Variable
6- Data types
7- Conditional statements
8- If
9- If else
10- If else if
11- Nested if
12- Switches
8
WRITTEN BY: TASAL
13- Iterative structure for while do while.
14- Loop
15- For
16- While
17- Do while
18- For each
19- Array
20- Single dimensional
21- Multi-dimensional
22- Goto
While loop
Is an undetermined loop.
Used for Uncountable iteration
Otherwise
For loop is determined loop
Used for countable iteration
Array
Array is the consecutive memory location with same name and type
Array declaration and initialization.
Int[] arr={2,4,5,66,33,2,22};
For (int i=0;i<arr.lenght;i++){
Console.writeline(arr[i]);
Example
Int[] arr=new int[10];
9
WRITTEN BY: TASAL
Arr[0]=30;
main لهprogram start ضروری ده ځکه دMain method لپاره یوNamespace د هر:نوټ
ضروری دهMain Method څخه کیږی نو ددی لپارهmethod
Example
Class program
Static void main(string[] ags)
Console.writeline(sum());
Console.readkey();
Static int sum()
Return(20+10);
Example
Namespace test
Class program
Static void main(string[] args)
Cal cal1=new cal();// object creation
Console.writeline(cal1.add(10,20)); console.readkey();
Class cal
Public int add(int a,int b)
Return(a+b);
10
WRITTEN BY: TASAL
}
}}
Class creation
Namespace test
Class program
Static void main(string[] args)
Student khan=new student(2133,’Khan’,’C#’,4000); // this is parameterize constructor
Khan.showInfo();
Console.readkey();
Public Class student
{ int id;
String name;
String program;
Int fee;
Public showInfo()
Console.writeline(id);
Console.writeline(name);
Console.writeline(program);
Console.writeline(fee);
Public Student(int sid, string sname, string sprogram, int sfee)
This.id=sid;
This.name=sname;
This.program=sprogram;
This.fee=sfee;
11
WRITTEN BY: TASAL
شیaccess کیmain method پهclass,method,constructor ددی لپاره چی زموږ:نوټ
. واوسی لکه په پورته میثال کیpublic نو باید چی
جوړ کړوکه هغهobj کوو د هغی لپاره باید چیaccess کیmain method چی پهclass هر:نوټ
. شیCreate ییobj نو باید چیuser define وی او کهbuilt-in
جوړobj کی یوmain method دی د دی لپاره باید چی پهbuilt-in class یوRandom لکه
. لکه لاندی.شی
Random obj1=nem Random();
دیnext لپاره چیrandom لری لکه دproperties اوmethods هرکلاس خپل:نوټ
Obj1.next(range value);
Obj1.next(1,100);
. کي ځای جوړویmemory لپاره پهobject د هر:Constructor functionality
. شیpublic بایدproperties لپاره باید چی کلاسdefault constructor د:نوټ
.لکه لاندی
Namespace test
Class program
Static void main(string[] args)
Chair a=new chair(); // this default constructor
a.cost=3000;
a.color=’Red’;
a.setting();
Class chair
Public Int cost;
12
WRITTEN BY: TASAL
PublicString color;
Public void setting()
Console.writeline(‘Now you are setting on chair which color is ‘+color +”and cost is “+ cost);
Game Project.
Namespace test
Class program
Static void main(string[] args){
Random obj=new Random();
Int b=Obj.next(1,100);
Int myValue;
Console.writeline(“What do you think which number is stored in random class?);
myValue=convert.toInt32(console.readline());
for(int a=o; a<=5; a++){
if(myValue> b)
Console.writeline(“Sorry brother random value is less then your number”);
Else if(myValue<b)
Console.writeline(“Sorry brother random value is greater then your number”);
Else if( myValue=b)
Console.writeline(“Congratulation You Wonnnnnnnnnnnnnnnnnnnnnnn”);
Break; /// it mean when value found do not go forward.
13
WRITTEN BY: TASAL
}
Console.readkey();
}// this is loop body.
Some built-in classes in C#.
Like
1-Math class // this is abstract class and its object cannot be create it
can be use directly like bellow
Math. Sin(a); it will show sin
Math.sqrt(a);// it will find the square of a number.
Math. Round(a); it will find the round of a number.
2-DateTime class
It is also a built-in abstract class it is used to show current date of the
system.
Like
Console.writeline(DateTime.now) ;// it will show full date.
Console.writeline(DateTime.now.day) ;// it will show day
Console.writeline(DateTime.now.addDay(7)) ;→
استفادهfunction ورځی وروسته به څوم تاریخ وی ددی لپاره دا۷ ددی پورته میثال څخه مقصد دادی چی
.کیږی
14
WRITTEN BY: TASAL
How to find age from date of birth?
DateTime dob;
Console.writeline(“Enter you are DOB.”);
Dob=convert.toDateTime(console.readline());
Console.writeline(DateTime.Today.Year-dob.year);
3-String class
This is built-in abstract class which have some string function.
Like
String a;
Console.writeline(“Enter Your Name”);
a=console.readline();
console.writeline(a.toUpper()); // this toUpper is a string class function.
Polymorphism or function overloading
. څخه دیpolymorphism ترسره کول غبارت دtasks باندی څوfunction په یو
Function overloading
To create multiple function by same name is called function
overloading.
15
WRITTEN BY: TASAL
Example
Class program
Static void main(string[] ags)
Console.writeline(sum(12,14));
Console.writeline(sum(“Siraj”,”Tasal”));
Console.readkey();
Static int sum(int a, int b)
Return(a+b);
Static string sum(string fn, string ln)
Return fn+” ”+ ln;
What is inheritance?
Father and child relationship is called inheritance.
Example
16
WRITTEN BY: TASAL
Namespace test
Class program
Static void main(string[] args)
Player ahmad=new player();
Ahmad.name=”Aahmad”;
Ahmad.fname=”Jalal”;
Ahmad.role=”Batsman”;
Ahmad.age=20;
Ahmad.show();
Console.readkey();
Class student
Public String name;
Public String fname;
Public int phone;
Public int age;
Class player : class student // we can inherit classes with colon (:) in C#.
Public string role;
Public int height;
Public double strike;
Public void show()
Console.writeline(this.name);
Console.writeline(this.fname);
Console.writeline(this.phone);
Console.writeline(this.age);
17
WRITTEN BY: TASAL
Console.writeline(this.role);
Console.writeline(this.height);
Console.writeline(this.strike);
Note: this is golden example for the inheritance concept;
لپاره چی هغه کی دی د شاګرد نوم پلارنوم عمر تلیفونstudent موږ غواړو چی یو کلاس جوړ کړود:نوټ
شمیره موجوده وی او اوس بیا غواړو چی داسی یو بل کلاس جوړ کړو د کرکت د لوبعاړی لپاره چی دا د شاکرد
دی پهrole, strike, height لکه د لوبعاړیproperties هم ولری او خپلیproperties کلاس
دوباره لیکلو تهproperties کلاسstudent کی هم موجودوی نو د کرکت د لوبعاړی په کلاس کی د
لکه په، لرو د دی ستونزی د حل لپارهconcept په نامه یوinheritance ضرورت نشته ځکه چی موږ د
.پورته میثال کی چی لیدل کیږی
Complex type variables in C#.
Enumeration
Structure
Enumeration
Enum is used to store multiple values but only digits like int type byte
type…..
Note: can access enum values through name.
Example
18
WRITTEN BY: TASAL
Class program
Enum direction : byte
Left=0; right,down,up
};
Static void main(string[] ags)
Direction a=direction.left;
Console.writeline(a);
Console.readkey();
Structure
Structure is used to store multiple values with different data type.
For structure we are using struct keyword.
Example
Class program
Struct student
Public string name;
Public string fname;
Public int age;
Static void main(string[] ags)
19
WRITTEN BY: TASAL
{
Student ahmad;
Ahmad.name=”ahmad”;
Ahmad.fname=”ali”;
Ahmad.age=22;
Console.writeline(ahmad.name);
Console.readkey();
Introduction To C# BY Sir Noorulhaq.
20
WRITTEN BY: TASAL
Windows Form Application
Messagebox.show(“This is C#
Introduction”,messageboxbutton.OkCancel,messageboxIcon.error,);
Button1.enabel=false;
This is used to disable the button
? helpbutton
This is used to help you about a specific topic;
Rules
Maximize and minimize should be false
Note: For this we are using helpprovider control In tools box
Approach
Right click on button or any other control →properties →help string on
help provider1 → write your help string like this is for printing.
Text_changed Event
When we brings changes in textbox automatically call function or every
things
Approach
Double click on text-box
Checkbox
21
WRITTEN BY: TASAL
If (checkbox1.checked)
Textbox1.visible =true;
Else
Textbox1.visible=false;
Example
If (checkbox1.checked)
Textbox1.Text =checkbox1.text.tostring();
Else
Textbox1.text=””;
CheckListbox
Group of checkbox;
Approach
Edit items
Trim()
It used to remove space;
Like
22
WRITTEN BY: TASAL
If(textbox1.text.trim() != “”)
{ checklistbox1.text=textbox1.text;
}
Else { Message;}
How to remove duplication
If(! checklistbox1.items.contain(textbox1.text))
{ checklistbox1.text=textbox1.text;
}
Else {Duplicate Value}
DateTime Packer
This option is used to select a date and time.
Its properties
Format→ long date and short date
Time→ it is used for time
ListView
It is used for interface like table.
23
WRITTEN BY: TASAL
How to take listview ?
How to add cols in listview?
How to add items in listview? For this use listviewitems class.
How to add sub items in listview for items?
There is two approach
- Properties
- Coding
Listview1.columns.add(“ID”); Listview1.columns.add(“Name”);
Listview1.gridlines=true;
Listview1.veiw= view.details; used to show columns
Example
Listviewites obj= new listviewitems(1);
Obj.subitems.add(“Khan”); Obj.subitems.add(“0779165118”);
Listview1.items.add(obj);
ContextMenueStriped
It is used to create menus like file edit help etc.
24
WRITTEN BY: TASAL
Combo Box and list Box
Both are same just in combo box we can select data with click but in list
box the data is already shown.
Both have two properties
Display Member
Value Member
LinkLabel
For this we are using diagnostic namespace
It is used for connection creation
For example
Process.start(“http://www.google.com”);
Process.start(“calc”);
Process.start(“excel”);
Process.start(“winword”);
Mask Textbox
It is used for security
User unable for wrong entry
25
WRITTEN BY: TASAL
Like
Click → setmask
NumericUpDown
It is used for selection
Database Connectivity
For db connection we are using the bellow namespace
Like
Using system.data.sqlclient
Note: These are important for db connection
Data Source=./PC Name/(LOCAL)
Initial Catalog Or Database =DB Name
Integrated Security= True/False/ SSPI.
Note: with sql server authentication mode we are using FALSE Keyword
Note: with windows authentication mode we are using TRUE keyword.
Now we are connect with windows authentication mode
26
WRITTEN BY: TASAL
Note: SSPI its better from FALSE AND TRUE
Con.open();
Con.close();
Con.state=connectionstate.open (); // for checking connection
DML Operation
1- Insertion
2- Selection
3- Deletion
4- Updating
Most Important Points
SQLCommand com=new sqlcommand();
This class has some properties
Like
Com.connection=con;
Com.commandtext=””;
Com.executeReader(); this is used to retrieve multiple cols data
Com.executeScalar(); this is used to retrieve single col data
Com.executeNonQuery(); this is used for insert, delete, update operations;
SQLCONNECTION con=new SQLCONNECTION();
Con.connectionString=””;
27
WRITTEN BY: TASAL
Master Form Or (MDI) Form
And
Login Form
. ویل کیږیMDI Form خلاصیږی دی تهForms وی چی په دی کی موږ سره ټولForm داسی یوMDI
How to use Timer?
DateTime dt= DateTime.now;
Label1.text= dt.tostring();
Call in form_load.
Timer1.start();
How to a form inside another form?
New_Student<FN> fm = new New_Student();
Fm.mdiParent=this;open inside the this
form
fm.Show();
Label
Auto size when we give auto size false then we can spread it
And
Duck it means Full.
Data Grade view
It is same with list view
It is used for showing the data.
28
WRITTEN BY: TASAL
Auto size column mode property
This is used to full fill data gradeview.
Best Query
Select * from student where id between 1 and 20 ;
select * from StudentInfo where StdID between 2 and 4;
Best Approach
When you have used built-in keyword as table name or column name like
password
select UserName,[Password] from [user]
enum class
is used for security.
MDI Form Approach
1- isMDIContainer= false from properties
2- new form object creation like
29
WRITTEN BY: TASAL
New_Student obj = new New_Student();
obj.MdiParent = this;
obj.Show();
Login Form Approach
1- open new form
2- go solution explorer then R click on program.cs
3- give login form name in function. Like
Application.Run(new loginform());
Some methods
Application.exit();
if (dt.Rows.Count > 0)
Form1 frm= new Form1()
This.hide();
Namespace for data table
System. Data;
30
WRITTEN BY: TASAL