Está en la página 1de 136

LAB REPORT

CSHAPE 1

Student:Nguyn Vn Tng
ID:09210071
Class:CDTH11

Contents
MODULE 1 ................................................................................................................... 9
EXERCISE 1 .................................................................................................................. 9
Problem .................................................................................................................... 9
Code Listing ............................................................................................................. 9
Execution Result ...................................................................................................... 9
EXERCISE 2 ................................................................................................................ 10
Problem .................................................................................................................. 10
Code Listing ........................................................................................................... 10
Execution Result .................................................................................................... 10
EXERCISE 3 ................................................................................................................ 11
Problem .................................................................................................................. 11
Code Listing ........................................................................................................... 11
Execution Result .................................................................................................... 12
EXERCISE 4 ................................................................................................................ 12
Problem .................................................................................................................. 12
Code Listing ........................................................................................................... 12
Execution Result .................................................................................................... 13
EXERCISE 5 ................................................................................................................ 13
Problem .................................................................................................................. 13
Code Listing ........................................................................................................... 13
Execution Result .................................................................................................... 14
EXERCISE 6 ................................................................................................................ 15
Problem .................................................................................................................. 15
Code Listing ........................................................................................................... 15
Execution Result .................................................................................................... 17
EXERCISE 7 ................................................................................................................ 17
Problem .................................................................................................................. 17
Code Listing ........................................................................................................... 17
Execution Result .................................................................................................... 18
EXERCISE 8 ................................................................................................................ 18
Problem .................................................................................................................. 18
Code Listing ........................................................................................................... 18
Execution Result .................................................................................................... 20
EXERCISE 9 ................................................................................................................ 20
2

Problem .................................................................................................................. 20
Code Listing ........................................................................................................... 20
Execution Result .................................................................................................... 22
EXERCISE 10 .............................................................................................................. 22
Problem .................................................................................................................. 22
Code Listing ........................................................................................................... 23
Execution Result .................................................................................................... 23
MODULE 2 ................................................................................................................. 24
EXERCISE 1 ................................................................................................................ 24
Problem .................................................................................................................. 24
Code Listing ........................................................................................................... 24
Execution Result .................................................................................................... 25
EXERCISE 2 ................................................................................................................ 26
Problem .................................................................................................................. 26
Code Listing ........................................................................................................... 26
Execution Result .................................................................................................... 27
EXERCISE 3 ................................................................................................................ 27
Problem .................................................................................................................. 27
Code Listing ........................................................................................................... 27
Execution Result .................................................................................................... 29
EXERCISE 5 ................................................................................................................ 31
Problem .................................................................................................................. 31
Code Listing ........................................................................................................... 31
Execution Result .................................................................................................... 33
EXERCISE 6 ................................................................................................................ 34
Problem .................................................................................................................. 34
Code Listing ........................................................................................................... 34
Execution Result .................................................................................................... 35
EXERCISE 7 ................................................................................................................ 35
Problem .................................................................................................................. 35
Code Listing ........................................................................................................... 36
Execution Result .................................................................................................... 37
EXERCISE 8 ................................................................................................................ 37
Problem .................................................................................................................. 37
Code Listing ........................................................................................................... 37
Execution Result .................................................................................................... 39
EXERCISE 9 ................................................................................................................ 39
Problem .................................................................................................................. 39
Code Listing ........................................................................................................... 39
3

Execution Result .................................................................................................... 41


EXERCISE 10 .............................................................................................................. 41
Problem .................................................................................................................. 41
Code Listing ........................................................................................................... 41
Execution Result .................................................................................................... 42
EXERCISE 11 .............................................................................................................. 42
Problem .................................................................................................................. 42
Code Listing ........................................................................................................... 42
Execution Result .................................................................................................... 44
EXERCISE 12 .............................................................................................................. 44
Problem .................................................................................................................. 44
Code Listing ........................................................................................................... 44
Execution Result .................................................................................................... 45
EXERCISE 13 .............................................................................................................. 46
Problem .................................................................................................................. 46
Code Listing ........................................................................................................... 46
Execution Result .................................................................................................... 48
EXERCISE 14 .............................................................................................................. 49
Problem .................................................................................................................. 49
Code Listing ........................................................................................................... 49
Execution Result .................................................................................................... 51
EXERCISE 15 .............................................................................................................. 52
Problem .................................................................................................................. 52
Code Listing ........................................................................................................... 52
Execution Result .................................................................................................... 54
EXERCISE 16 .............................................................................................................. 55
Problem .................................................................................................................. 55
Code Listing ........................................................................................................... 55
Execution Result .................................................................................................... 56
EXERCISE 18 .............................................................................................................. 56
Problem .................................................................................................................. 56
Code Listing ........................................................................................................... 56
Execution Result .................................................................................................... 58
EXERCISE 19 .............................................................................................................. 60
Problem .................................................................................................................. 60
Code Listing ........................................................................................................... 60
Execution Result .................................................................................................... 60
EXERCISE 20 .............................................................................................................. 60
Problem .................................................................................................................. 60
Code Listing ........................................................................................................... 61
4

Execution Result .................................................................................................... 61


EXERCISE 21 .............................................................................................................. 61
Problem .................................................................................................................. 61
Code Listing ........................................................................................................... 61
Execution Result .................................................................................................... 61
EXERCISE 22 .............................................................................................................. 61
Problem .................................................................................................................. 61
Code Listing ........................................................................................................... 61
Execution Result .................................................................................................... 61
MODULE 3 ................................................................................................................. 62
EXERCISE 1 ................................................................................................................ 62
Problem .................................................................................................................. 62
Code Listing ........................................................................................................... 62
Execution Result .................................................................................................... 64
EXERCISE 2 ................................................................................................................ 64
Problem .................................................................................................................. 64
Code Listing ........................................................................................................... 64
Execution Result .................................................................................................... 66
EXERCISE 3 ................................................................................................................ 66
Problem .................................................................................................................. 66
Code Listing ........................................................................................................... 66
Execution Result .................................................................................................... 67
EXERCISE 4 ................................................................................................................ 68
Problem .................................................................................................................. 68
Code Listing ........................................................................................................... 68
Execution Result .................................................................................................... 71
EXERCISE 5 ................................................................................................................ 71
Problem .................................................................................................................. 71
Code Listing ........................................................................................................... 71
Execution Result .................................................................................................... 74
EXERCISE 6 ................................................................................................................ 75
Problem .................................................................................................................. 75
Code Listing ........................................................................................................... 75
Execution Result .................................................................................................... 78
EXERCISE 7 ................................................................................................................ 79
Problem .................................................................................................................. 79
Code Listing ........................................................................................................... 79
Execution Result .................................................................................................... 81
EXERCISE 8 ................................................................................................................ 81
5

Problem .................................................................................................................. 81
Code Listing ........................................................................................................... 81
Execution Result .................................................................................................... 83
EXERCISE 9 ................................................................................................................ 85
Problem .................................................................................................................. 85
Code Listing ........................................................................................................... 85
Execution Result .................................................................................................... 86
EXERCISE 10 .............................................................................................................. 87
Problem .................................................................................................................. 87
Code Listing ........................................................................................................... 87
Execution Result .................................................................................................... 89
EXERCISE 11 .............................................................................................................. 90
Problem .................................................................................................................. 90
Code Listing ........................................................................................................... 91
Execution Result .................................................................................................... 91
EXERCISE 12 .............................................................................................................. 91
Problem .................................................................................................................. 91
Code Listing ........................................................................................................... 92
Execution Result .................................................................................................... 92
MODULE 4 ................................................................................................................. 92
EXERCISE 1 ................................................................................................................ 92
Problem .................................................................................................................. 92
Code Listing ........................................................................................................... 92
Execution Result .................................................................................................... 95
EXERCISE 2 ................................................................................................................ 97
Problem .................................................................................................................. 97
Code Listing ........................................................................................................... 97
Execution Result .................................................................................................... 97
EXERCISE 3 ................................................................................................................ 97
Problem .................................................................................................................. 97
Code Listing ........................................................................................................... 97
Execution Result .................................................................................................... 98
EXERCISE 4 ................................................................................................................ 98
Problem .................................................................................................................. 98
Code Listing ........................................................................................................... 98
Execution Result .................................................................................................... 98
EXERCISE 5 ................................................................................................................ 98
Problem .................................................................................................................. 98
Code Listing ........................................................................................................... 98
6

Execution Result .................................................................................................... 98


EXERCISE 6 ................................................................................................................ 99
Problem .................................................................................................................. 99
Code Listing ........................................................................................................... 99
Execution Result .................................................................................................... 99
MODULE 5 ................................................................................................................. 99
EXERCISE 1 ................................................................................................................ 99
Problem .................................................................................................................. 99
Code Listing ........................................................................................................... 99
Execution Result .................................................................................................. 100
EXERCISE 2 .............................................................................................................. 100
Problem ................................................................................................................ 100
Code Listing ......................................................................................................... 100
Execution Result .................................................................................................. 100
EXERCISE 3 .............................................................................................................. 100
Problem ................................................................................................................ 100
Code Listing ......................................................................................................... 100
Execution Result .................................................................................................. 104
EXERCISE 4 .............................................................................................................. 107
Problem ................................................................................................................ 107
Code Listing ......................................................................................................... 108
Execution Result .................................................................................................. 108
EXERCISE 5 .............................................................................................................. 108
Problem ................................................................................................................ 108
Code Listing ......................................................................................................... 108
Execution Result .................................................................................................. 111
MODULE 6 ............................................................................................................... 112
EXERCISE 1 .............................................................................................................. 112
Problem ................................................................................................................ 112
Code Listing ......................................................................................................... 112
Execution Result .................................................................................................. 117
EXERCISE 2 .............................................................................................................. 118
Problem ................................................................................................................ 118
Code Listing ......................................................................................................... 118
Execution Result .................................................................................................. 122
MODULE 7 ............................................................................................................... 123
EXERCISE 1 .............................................................................................................. 123
7

Problem ................................................................................................................ 123


Code Listing ......................................................................................................... 124
Execution Result .................................................................................................. 126
EXERCISE 2 .............................................................................................................. 130
Problem ................................................................................................................ 130
Code Listing ......................................................................................................... 130
Execution Result .................................................................................................. 130
EXERCISE 3 .............................................................................................................. 130
Problem ................................................................................................................ 130
Code Listing ......................................................................................................... 130
Execution Result .................................................................................................. 131
EXERCISE 4 .............................................................................................................. 132
Problem ................................................................................................................ 132
Code Listing ......................................................................................................... 132
Execution Result .................................................................................................. 134
EXERCISE 5 .............................................................................................................. 134
Problem ................................................................................................................ 134
Code Listing ......................................................................................................... 134
Execution Result .................................................................................................. 136

Module 1
Exercise 1
Problem
Mc ch:
S dng cc properties v methods ca cc i tng trong ng dng Console.
Yu cu:
Vit ng dng dng Console xut li cho.
Yu cu xut ra li cho sau:

Welcome to
C# 2010 Programming!
Programming by your name

Code Listing
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Text;

namespace Bai01
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to");
Console.WriteLine("C# 2010 Programming!");
Console.WriteLine("Programming by Tung");
Console.ReadLine();
}
}
}

Execution Result

Exercise 2
Problem
Mc ch:
S dng cc Properties v Methods ca cc i tng trong ng dng Console Kt hp
nh dng xut d liu.
Yu cu:

+ Ro cc statement trong hm Main ca bi 1 chuyn sang dng comment.

Code Listing
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Text;

namespace Bai02
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("{0}\n{1}","Welcome to","C# 2010 Programming!");
Console.WriteLine("Programming by Tung");
Console.ReadLine();
}
}
}

Execution Result

10

Exercise 3
Problem
Mc ch:
S dng mt s hm ton hc v nhp d liu t bn phm Kt hp nh dng xut d liu.
Yu cu:

+ To Project mi vi tn l ThaoTacSo:
Khi chy ch ng t nh xut ra yu cu nhp vo hai s t bn phm xut ra kt qu
tng ca hai s va nhp.
Xut ra m hnh yu cu c dng:
Nhap So Thu Nhat A: ??
Nhap So Thu Hai B: ??
Tong cua ?? Va ?? La: ??

Code Listing
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Text;

namespace Bai03
{
class Program
{
static void Main(string[] args)
{
int a, b, nTong = 0;
Console.Clear();
Console.Write("Nhap So Thu Nhat A: ");
a= Convert.ToInt32(Console.ReadLine());
Console.Write("Nhap So Thu Hai B: ");
b = Convert.ToInt32(Console.ReadLine());
nTong = a + b;
Console.WriteLine("Tong Cua "+a+" Va "+b+" La "+nTong);
Console.WriteLine("Programming by Tung");
Console.ReadLine();
}
}
}

11

Execution Result

Exercise 4
Problem
Mc ch:
S dng mt s hm ton hc v nhp d liu t bn phm Kt hp nh dng xut d liu.
Yu cu:

+ To Project mi vi tn l TinhDienTich:
+ Khi chy ch ng t nh xut ra yu cu nhp vo hai cnh ca mt t gicvung
xut ra kt qu chu vi, din tch.

Code Listing
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Text;

namespace Bai04
{
class Program
{
static void Main(string[] args)
{
int dai, rong, chuvi = 0,dt=0;
Console.Clear();
Console.WriteLine("==========Tinh Chu Vi & Dien Tich HCN=========== ");
Console.Write("Nhap Chieu Dai: ");
dai = Convert.ToInt32(Console.ReadLine());
Console.Write("Nhap Chieu Rong: ");
rong = Convert.ToInt32(Console.ReadLine());
chuvi = (dai + rong) * 2;
dt = dai * rong;
Console.WriteLine("Chu Vi = "+chuvi+"\nDien Tich = "+dt);
Console.WriteLine("\nProgramming by Tung");
Console.ReadLine();
}
}
}

12

Execution Result

Exercise 5
Problem
Mc ch:
S dng mt s hm ton hc v nhp d liu t bn phm Kt hp nh dng xut d liu.
Yu cu:

+ To Project mi vi tn l PhuongTrinhBac1:
+ Gii v bin lun ph n g t nh bc 1 : ax+b=0
+ Sinh vin ch rng ph ng t nh c 3 trng hp: v nghim, v s nghim v c mt
nghim

Code Listing
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Text;

namespace Bai05
{
class Program
{
static void Main(string[] args)
{
int a, b;
float x;
Console.Clear();
Console.WriteLine("==========Giai Va Bien Luan Phuong Trinh Bac
Nhat=========== ");
Console.Write("Nhap a: ");
a = Convert.ToInt32(Console.ReadLine());
Console.Write("Nhap b: ");
b = Convert.ToInt32(Console.ReadLine());
GiaiPTBacNhat(a, b);
//Console.WriteLine("");
Console.WriteLine("\nProgramming by Tung");

13

Console.ReadLine();
}
public static void GiaiPTBacNhat(int a, int b)
{
double x;
if (a == 0)
{
if (b == 0)
{
Console.WriteLine("Phuong Trinh Vo So Nghiem");
}
else
{
Console.WriteLine("Phuong Trinh Vo Nghiem");
}
}
else
{
x = -b*1.0 / a;
Console.WriteLine("Phuong Trinh Co 1 Nghiem = " + x);
}
}
}
}

Execution Result

14

Exercise 6
Problem
Mc ch:
S dng mt s hm ton hc v nhp d liu t bn phm Kt hp nh dng xut d liu.(
lm quen class Math)

Math.Pow(x,y) ,Math.Sqrt(x) ,Math.Round(x,2)


Yu cu:

+ To Project mi vi tn l PhuongTrinhBac2:
+ Gii v bin lun ph n g t nh bc 2

Code Listing
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Bai06
{
class Program
{
static void Main(string[] args)
{
int a=0, b=0,c=0;
double x1,x2;
Console.Clear();
Console.WriteLine("==========Giai Va Bien Luan Phuong Trinh Bac
Hai=========== ");
Console.Write("Nhap a: ");
a = Convert.ToInt32(Console.ReadLine());
Console.Write("Nhap b: ");
b = Convert.ToInt32(Console.ReadLine());
Console.Write("Nhap c: ");
c = Convert.ToInt32(Console.ReadLine());
if (a == 0)
{
GiaiPTBacNhat(a, b);

15

}
else
{
double delta = b*b-4*a*c;
if (delta < 0)
{
Console.WriteLine("Phuong Trinh Vo Nghiem");
}
else if (delta == 0)
{
x1 = -b * 1.0 / (2*a);
Console.WriteLine("Phuong Trinh Co Nghiem Kep \nx1 = x2 = " + x1);
}
else
{
x1 = (-b-Math.Sqrt(delta))/(2*a);
x2 = (-b + Math.Sqrt(delta)) / (2 * a);
Console.WriteLine("Phuong Trinh Co 2 Nghiem Phan Biet \nx1 =
"+x1+"\nx2 = "+x2);
}
}
Console.WriteLine("\nProgramming by Tung");
Console.ReadLine();
}
public static void GiaiPTBacNhat(int a, int b)
{
double x;
if (a == 0)
{
if (b == 0)
{
Console.WriteLine("Phuong Trinh Vo So Nghiem");
}
else
{
Console.WriteLine("Phuong Trinh Vo Nghiem");
}
}
else
{
x = -b * 1.0 / a;
Console.WriteLine("Phuong Trinh Co 1 Nghiem = " + x);
}
}
}
}

16

Execution Result

Exercise 7
Problem
Mc ch:
tip tc lm quen vi class Math
Yu cu:

+ Nhp 1 gc x. Tnh v xut sinx, cosx, tgx, cotgx.

Code Listing
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Bai07
{
class Program
{
static void Main(string[] args)
{
double a = 0, rad;

17

Console.Clear();
Console.WriteLine("==========Cac Ham Luong Giac=========== ");
Console.Write("Nhap Vao 1 Goc: ");
a = Convert.ToInt32(Console.ReadLine());
rad = a * Math.PI / 180;
Console.Write("Sin({0}) = {1}", a, Math.Sin(rad));
Console.Write("\nCos({0}) = {1}", a, Math.Cos(rad));
Console.Write("\nTan({0}) = {1}", a, Math.Tan(rad));
Console.Write("\nCogTan({0}) = {1}", a, 1 / Math.Tan(rad));
Console.WriteLine("\n\nProgramming by Tung");
Console.ReadLine();
}
}
}

Execution Result

Exercise 8
Problem
Mc ch:
S dng mt s hm lng gic v nhp d liu t bn phm Kt hp nh dng xut d
liu.( tip tc lm quen vi class Math)
Yu cu:

+ To Project mi vi tn l ChuViDienTichTamGiac:
+Nhp cnh a>0, b>0, c>0. Nu a, b, c to thnh tam gic th h y tnh v xut chu vi,
din tch hnh tam gic. Ngc li thng bo Khng to thnh tam gic
HD: cv=a+b+c, p=cv/2 v dt=p* (p-a) (p-b) (p-c)

Code Listing
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Text;

18

namespace Bai08
{
class Program
{
static void Main(string[] args)
{
double a,b,c;
Console.Clear();
Console.WriteLine("==========Tinh Chu Vi Va Dien Tich Tam Giac===========
");
a = Input('a');
b = Input('b');
c = Input('c');
if (!KiemTraTamGiac(a,b,c))
{
Console.WriteLine("\nKhong Tao Thanh Tam Giac");
}
else
{
Console.WriteLine("\nChu Vi = {0}",a+b+c);
double p = (a + b + c) / 2;
Console.WriteLine("\nDien Tich = {0}", Math.Sqrt(p*(p-a)*(p-b)*(pc)));
}
Console.WriteLine("\n\nProgramming by Tung");
Console.ReadLine();
}
public static double Input(char bien)
{
double x;
do
{
Console.Write("\nNhap {0}: ",bien);
x = Convert.ToDouble(Console.ReadLine());
} while (x <= 0);
return x;
}
public static bool KiemTraTamGiac(double a, double b, double c)
{
if (a + b <= c || a + c <= b || b + c <= a)
return false;
else return true;
}
}
}

19

Execution Result

Exercise 9
Problem
Mc ch:
S dng hm ton hc v nhp d liu t bn phm Kt hp nh dng xut d liu.
Yu cu:

+ To Project mi vi tn l TinhTongChuoiSo: + Nhp x, n tnh tng chui s sau (lm


trn 3 ch s):
S(x,n) = x+x2/2! + x3/3! + + xn/n!

Code Listing
using System;

20

using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Bai09
{
class Program
{
static void Main(string[] args)
{
int x, n;
double Tong = 0;
Console.Clear();
Console.WriteLine("==========Tinh Tong Chuoi So=========== ");
x = Input('x');
n = Input('n');
for (int i = 1; i <= n; i++)
{
Tong += (Math.Pow(x, i) / GiaiThua(i));
}
Console.WriteLine("\nS({0},{1}) = {2}", x, n, Math.Round(Tong, 3));
Console.WriteLine("\n\nProgramming by Tung");
Console.ReadLine();
}
public static int Input(char bien)
{
int x;
do
{
Console.Write("\nNhap {0}: ", bien);
x = Convert.ToInt32(Console.ReadLine());
} while (x <= 0);
return x;
}
public static int GiaiThua(int x)
{
int n=1;
for (int i = 1; i <= x; i++)
{
n *= i;
}
return n;
}
}
}

21

Execution Result

Exercise 10
Problem
Mc ch:
S dng hm ton hc v nhp d liu t bn phm Kt hp nh dng xut d liu.
Yu cu:

+ To Project mi vi tn l SoGaSoCho: + Tm s g v s ch, bit:


Va g va ch
B li cho trn
22

Ba m i su con
Mt tr m chn chn
Gi :
X + Y = 36
2 + 4 = 100
Vi X l s g, Y l s Ch

Code Listing
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Text;

namespace Bai10
{
class Program
{
static void Main(string[] args)
{
int ga, cho;
Console.Clear();
Console.WriteLine("============================== ");
Console.WriteLine("Vua Ga Vua Cho");
Console.WriteLine("Bo Lai Cho Tron");
Console.WriteLine("Ba Muoi Sau Con");
Console.WriteLine("Mot Tram Chan Chan");
Console.WriteLine("============================== ");
//100 = 72-2*cho+4*cho = 72 +2*cho
cho = (100 - 72) / 2;
ga = 36 - cho;
Console.WriteLine("So Ga = "+ga);
Console.WriteLine("So Cho ="+cho);
Console.WriteLine("\n\nProgramming by Tung");
Console.ReadLine();
}
}
}

Execution Result

23

Module 2
Exercise 1
Problem
Yu Cu
Thit k form nh hnh

Code Listing
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;

24

using
using
using
using

System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace Bai01
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnHienThi_Click(object sender, EventArgs e)
{
txtHienThi.Text = txtNhapPass.Text;
}
private void btnTiep_Click(object sender, EventArgs e)
{
txtHienThi.Text = "";
txtNhapPass.Clear();
txtNhapPass.Focus();
}
private void btnDong_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

Execution Result

25

Exercise 2
Problem
Mc ch:
S dng cc s kin (event) c bn trn Form
Yu Cu
Thit k form ch cha 1 button (xem hnh)

Code Listing
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace Bai02
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
MessageBox.Show("Hi,Welcome to C# Programming!");
}
private void btnClickMe_Click(object sender, EventArgs e)
{
MessageBox.Show("Button was clicked");
}
private void Form1_Click(object sender, EventArgs e)
{
MessageBox.Show("Form was clicked");
}
}
}

26

Execution Result

Exercise 3
Problem
Thit k giao din nh hnh

Code Listing
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;

27

using System.Windows.Forms;
namespace Bai03
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button4_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnHoLot_Click(object sender, EventArgs e)
{
lblHoTen.Text = txtHo.Text;
}
private void btnTen_Click(object sender, EventArgs e)
{
lblHoTen.Text = txtTen.Text;
}
private void btnHoVaTen_Click(object sender, EventArgs e)
{
lblHoTen.Text = txtHo.Text +" "+ txtTen.Text;
}
}
}

28

Execution Result

29

30

Exercise 5
Problem
Yu Cu:
Thit k giao din nh hnh
Yu cu
1. khi Form load.
a. Radi obut t on Red c chn mc nh
b. Con tr xut hin ngay ti Nhp tn.
2. Khi g tn vo Nhp tn (g k t no th lable lp trnh chy song song cng gi tr
trong nhp tn)

Code Listing
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace Bai05
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)

31

{
pictureBox1.Image = imageList1.Images[0];
pictureBox2.Image = imageList1.Images[1];
//lblLapTrinh.ForeColor = Color.Red;
//txtNhapTen.ForeColor = Color.Red;
}
private void pictureBox1_Click(object sender, EventArgs e)
{
pictureBox2.Visible = true;
pictureBox1.Visible = false;
}
private void pictureBox2_Click(object sender, EventArgs e)
{
pictureBox2.Visible = false;
pictureBox1.Visible = true;
}
private void txtNhapTen_TextChanged(object sender, EventArgs e)
{
lblLapTrinh.Text = txtNhapTen.Text;
}
private void rbnRed_CheckedChanged(object sender, EventArgs e)
{
lblLapTrinh.ForeColor = Color.Red;
txtNhapTen.ForeColor = Color.Red;
}
private void rbnGreen_CheckedChanged(object sender, EventArgs e)
{
lblLapTrinh.ForeColor = Color.Green;
txtNhapTen.ForeColor = Color.Green;
}
private void rbnBlue_CheckedChanged(object sender, EventArgs e)
{
lblLapTrinh.ForeColor = Color.Blue;
txtNhapTen.ForeColor = Color.Blue;
}
private void rbnBlack_CheckedChanged(object sender, EventArgs e)
{
lblLapTrinh.ForeColor = Color.Black;
txtNhapTen.ForeColor = Color.Black;
}
private void cbxBold_CheckedChanged(object sender, EventArgs e)
{
lblLapTrinh.Font = new Font(lblLapTrinh.Font.Name,
lblLapTrinh.Font.Size,lblLapTrinh.Font.Style ^ FontStyle.Bold);
}
private void cbxItalic_CheckedChanged(object sender, EventArgs e)
{

32

lblLapTrinh.Font = new Font(lblLapTrinh.Font.Name, lblLapTrinh.Font.Size,


lblLapTrinh.Font.Style ^ FontStyle.Italic);
}
private void cbxUnderline_CheckedChanged(object sender, EventArgs e)
{
lblLapTrinh.Font = new Font(lblLapTrinh.Font.Name, lblLapTrinh.Font.Size,
lblLapTrinh.Font.Style ^ FontStyle.Underline);
}
private void btnThoat_Click(object sender, EventArgs e)
{
if (MessageBox.Show("thoat y/n?","thong
bao",MessageBoxButtons.YesNo)==DialogResult.Yes)
{
this.Close();
}
}
}
}

Execution Result

33

Exercise 6
Problem
Vit lnh ch ng t nh hot ng nh sau:
Khi form va load ln th:
Con tr c t ti v tr Name
Hnh CDRom ln hin ngc li hnh nh n.
Hng dn: hiu chnh property Visible ca picSmall thnh false (trong lc thit k)
a cht vo hnh CDRom (ln, nh) hin ln tooltip Click Me
Hiu chnh TabIndex sao cho hp l (Tham kho hnh vo Menu View\Tab Order)

Code Listing
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace Bai06
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnDisplay_Click(object sender, EventArgs e)
{
lblMessage.Text = txtName.Text +" :" +txtMessage.Text;
}
private void btnClear_Click(object sender, EventArgs e)
{
txtMessage.Clear();
txtName.Clear();
}
private void btnExit_Click(object sender, EventArgs e)
{
this.Close();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
pictureBox1.Visible = false;
pictureBox2.Visible = true;
}

34

private void pictureBox2_Click(object sender, EventArgs e)


{
pictureBox1.Visible = true;
pictureBox2.Visible = false;
}
private void rbnRed_CheckedChanged(object sender, EventArgs e)
{
lblMessage.ForeColor = Color.Red;
}
private void rbnGreen_CheckedChanged(object sender, EventArgs e)
{
lblMessage.ForeColor = Color.Green;
}
private void rbnBlue_CheckedChanged(object sender, EventArgs e)
{
lblMessage.ForeColor = Color.Blue;
}
private void rbnBlack_CheckedChanged(object sender, EventArgs e)
{
lblMessage.ForeColor = Color.Black;
}
private void cbxMessageVisible_CheckedChanged(object sender, EventArgs e)
{
lblMessage.Visible = cbxMessageVisible.Checked;
}
}
}

Execution Result

Exercise 7
Problem
Mc ch:
Kt hp d dng component ToolTip trn cc control
Yu cu
1. Khi ch ng trnh va thc thi.
a. Form c hin th gia mn hnh
b. Cc i tng c neo sao cho khi ngi dng thay i kch thc
form th cc i tng c resize kch thc sao cho d nhn
c. picTurnOn c hin th, picTurnOff c n ngay bn di picTurnOn.
35

Khi ngi dng a chut vo picTurnOn s xut hin tip Click me to Turn OFF
the Light!, v ngc li trn picTurnOFF.
d. Hin tn mc nh vo Name e. Lable ngay bn di pictureBox hin th thng
bo

Jack. Turn Off the Light ,please!

Code Listing

36

Execution Result

Exercise 8
Problem
Mc ch: Lp trnh bin c trn cc i tng c to ng lc thc thi(run time)
Yu cu
Thit k form gm 2 button Add v Remove. Khi ngi s dng Click v button
Add, ch ng trnh s pht sinh ng 1 button trn form (mi button l mt Element
th n). Khi button Remove c Click, th button trn cng s c remove. (C th
hnh dung y l mt Stack).
Khi ngi dng Click vo mt Element no th s hin th trng thi ca Element
ln mt label pha trn form.

Code Listing
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;

37

using
using
using
using

System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace Bai08
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int i = 0;
private void btnAdd_Click(object sender, EventArgs e)
{
if (i <= 7)
{
Button b = new Button();
b.Size = new Size(60, 25);
b.Text = "button " + i.ToString();
i++;
b.Name = "button " + i.ToString();
b.Location = new System.Drawing.Point((panel1.Width - b.Width) / 2,
panel1.Height + 25 - (i+1) * 25);
b.Click += new EventHandler(this.button_click);
panel1.Controls.Add(b);
}
else
{
MessageBox.Show("het them dc roi cha noi");
}
}
public void button_click(object sender, EventArgs e)
{
Button b = (Button)sender;
lblStatus.Text ="Status : "+b.Text+" was clicked!!!";
}
private void btnRemove_Click(object sender, EventArgs e)
{
if (i > 0)
{
panel1.Controls.RemoveAt(i-1);
i--;
}
else
{
MessageBox.Show("het xoa dc roi cha noi");
}
}
}
}

38

Execution Result

Exercise 9
Problem
Mc ch:
S dng cc dialog c cung cp bi C#.
S dng RichTextBox
Yu cu
Ex1: Using Common Dialog Boxes

Code Listing
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace Bai09
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnOpen_Click(object sender, EventArgs e)
{

39

openFileDialog1.Filter = "(*.txt)|*.txt|(*.rtf)|*.rft";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
rtbDisplay.Clear();
rtbDisplay.LoadFile(openFileDialog1.FileName,RichTextBoxStreamType.PlainText);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
saveFileDialog1.Filter = "(*.txt)|*.txt|(*.doc)|*.doc";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
rtbDisplay.SaveFile(saveFileDialog1.FileName,
RichTextBoxStreamType.PlainText);
}
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnColor_Click(object sender, EventArgs e)
{
if (colorDialog1.ShowDialog() == DialogResult.OK)
{
rtbDisplay.SelectionColor = colorDialog1.Color;
}
}
private void btnFont_Click(object sender, EventArgs e)
{
if (fontDialog1.ShowDialog() == DialogResult.OK)
{
rtbDisplay.Font = fontDialog1.Font;
}
}
}
}

40

Execution Result

Exercise 10
Problem
Mc ch:
S dng i tng LinkLable lin kt n mt WebSite, m ng dng
Yu cu: Using LinkLabel Controls (page 456 )

Code Listing
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace Bai10
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void lnkWeb_LinkClicked(object sender, LinkLabelLinkClickedEventArgs
e)
{
System.Diagnostics.Process.Start("IExplore", "http://www.google.com.vn");

41

}
private void lnkCalculator_LinkClicked(object sender,
LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start("calc.exe");
}
private void lnlOpenC_LinkClicked(object sender, LinkLabelLinkClickedEventArgs
e)
{
System.Diagnostics.Process.Start("c://");
}
}
}

Execution Result

Exercise 11
Problem
Mc ch: S dng GroupBox v Panel
Yu cu : Using GroupBox and Panel Controls

Code Listing
using
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;
System.IO;

42

namespace Bai11
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//FileInfo f = null;
private void Form1_Load(object sender, EventArgs e)
{
//f= new FileInfo(pictureBox1.n
//f = new FileInfo(pictureBox1.Image.ToString());
//lblFileSize.Text = "File Size: "+f.Length.ToString();
//MessageBox.Show( pictureBox1.Image.
//FileInfo f = new FileInfo(pictureBox1.ImageLocation.ToString());
//MessageBox.Show(pictureBox1.ImageLocation);
lblDateLastModified.Text = "Date last modified : ";
lblDateLastAccessed.Text = "Date last accessed : ";
}
private void btnBrowse_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
FileInfo f = new FileInfo(openFileDialog1.FileName);
lblFileSize.Text = "File Size: " + f.Length.ToString();
lblDateLastModified.Text = "Date last modified :
"+f.LastWriteTime.ToString();
lblDateLastAccessed.Text = "Date last accessed :
"+f.LastAccessTime.ToString();
pictureBox1.Image = new Bitmap(openFileDialog1.FileName);
//MessageBox.Show(openFileDialog1.FileName.ToString());
}
}
}
}

43

Execution Result

Exercise 12
Problem
Mc ch:
S dng ListBox, CheckListBox, Combobox

Code Listing
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace Bai12
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{

44

string s = checkedListBox1.SelectedItem.ToString();
if(e.NewValue == CheckState.Checked)
{
lbxListBox.Items.Add(s);
}
else
{
lbxListBox.Items.Remove(s);
}
}
private void btnDone_Click(object sender, EventArgs e)
{
StringBuilder str = new StringBuilder();
if(lbxListBox.SelectedItems.Count >0)
{
str.Append("Ban da chon \n\n");
foreach (string s in lbxListBox.SelectedItems)
{
str.Append(s + "\n");
}
}
else
{
str.Append("Ban ko chon muc nao");
}
MessageBox.Show(str.ToString(), "tinh trang chon", MessageBoxButtons.OK,
MessageBoxIcon.Information);
}
}
}

Execution Result

45

Exercise 13
Problem
Mc ch:
Thao tc d liu s trn Listbox

Code Listing
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

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

private void btnCapNhat_Click(object sender, EventArgs e)


{
lstA.Items.Add(txtNhap.Text);
txtNhap.Clear();
txtNhap.Focus();
}
private void btnTong_Click(object sender, EventArgs e)
{
int tong = 0;
for (int i = 0; i < lstA.Items.Count; i++)
{
tong += int.Parse(lstA.Items[i].ToString());
}

46

MessageBox.Show("tong danh sach = "+tong.ToString());


}
private void btnKetThuc_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnXoaDauCuoi_Click(object sender, EventArgs e)
{
if (lstA.Items.Count > 1)
{
lstA.Items.RemoveAt(lstA.Items.Count - 1);
lstA.Items.RemoveAt(0);
}
else
{
MessageBox.Show("danh sach chi con mot phan tu hoac ko co phan tu
nao");
}
}
private void btnXoaDangChon_Click(object sender, EventArgs e)
{
for (int i = 0; i < lstA.Items.Count;i++ )
{
if (lstA.GetSelected(i))
{
lstA.Items.RemoveAt(i);
i--;
}
}
}
private void btnTangLen2_Click(object sender, EventArgs e)
{
if (lstA.Items.Count > 0)
{
for (int i = 0; i < lstA.Items.Count; i++)
{
int a = int.Parse(lstA.Items[i].ToString()) + 2;
lstA.Items.RemoveAt(i);
lstA.Items.Insert(i, a.ToString());
}
}
}
private void btnThayBinhPhuong_Click(object sender, EventArgs e)
{
if (lstA.Items.Count > 0)
{
for (int i = 0; i < lstA.Items.Count; i++)
{
int a = int.Parse(lstA.Items[i].ToString());
a = a * a;
lstA.Items.RemoveAt(i);
lstA.Items.Insert(i, a.ToString());
}
}
}

47

private void btnChonSoChan_Click(object sender, EventArgs e)


{
lstA.ClearSelected();
for (int i = 0; i < lstA.Items.Count; i++)
{
int a = int.Parse(lstA.Items[i].ToString());
if (a % 2 == 0)
lstA.SetSelected(i, true);
}
}
private void btnChonSoLe_Click(object sender, EventArgs e)
{
lstA.ClearSelected();
for (int i = 0; i < lstA.Items.Count; i++)
{
int a = int.Parse(lstA.Items[i].ToString());
if (a % 2 != 0)
lstA.SetSelected(i, true);
}
}
}
}

Execution Result

48

Exercise 14
Problem
Yu cu
Thit k form v thc hin cc chc n ng sau
- Quy nh form hin th gia mn hnh. Khng cho ngi s dng thay i kch thc form.
- Quy nh vic di chuyn Tab hp l.
- Cc ListBox c php chn nhiu mc (kt hp gia phm Shift, Control v chut)
- Khi ngi s dng Click nt Cp nht hoc nhn phm Enter th mt nh nhp tn sinh
vin t textbox vo danh sch lp A (khng chp nhn d liu rng). Theo
ngi s dng c th chn lp cp nht t combobox lp.
- Cc nt > v < khi c Click s di chuyn tt c cc mc ang chn sang ListBox
bn kia t ng ng.
- Cc nt >> v << khi c Click s di chuyn ton cc mc sang Listbox bn kia t ng
ng.
- Nt lnh Xa lp A, Xa lp B cho php xa cc mc ang chn trong list hin hnh.

Code Listing
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace Bai14
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btbCapNhat_Click(object sender, EventArgs e)
{
if (txtNhap.Text != "")
{
lstA.Items.Add(txtNhap.Text);

49

txtNhap.Clear();
txtNhap.Focus();
}
}
private void btnKetThuc_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnRight_Click(object sender, EventArgs e)
{
for(int i = 0 ; i < lstA.Items.Count ; i++)
{
if(lstA.GetSelected(i))
{
lstB.Items.Add(lstA.Items[i].ToString());
lstA.Items.RemoveAt(i);
i--;
}
}
}
private void btnDoubleRight_Click(object sender, EventArgs e)
{
for (int i = 0; i < lstA.Items.Count; i++)
{
lstB.Items.Add(lstA.Items[i].ToString());
lstA.Items.RemoveAt(i);
i--;
}
}
private void btnLeft_Click(object sender, EventArgs e)
{
for (int i = 0; i < lstB.Items.Count; i++)
{
if (lstB.GetSelected(i))
{
lstA.Items.Add(lstB.Items[i].ToString());
lstB.Items.RemoveAt(i);
i--;
}
}
}
private void btnDoubleLeft_Click(object sender, EventArgs e)
{
for (int i = 0; i < lstB.Items.Count; i++)
{
lstA.Items.Add(lstB.Items[i].ToString());
lstB.Items.RemoveAt(i);
i--;
}
}
private void btnXoaLopA_Click(object sender, EventArgs e)
{
lstA.Items.Clear();
}

50

private void btnXoaLopB_Click(object sender, EventArgs e)


{
lstB.Items.Clear();
}
private void cpNhtLpBToolStripMenuItem_Click(object sender, EventArgs e)
{
if (txtNhap.Text != "")
{
lstB.Items.Add(txtNhap.Text);
txtNhap.Clear();
txtNhap.Focus();
}
}
}
}

Execution Result

51

Exercise 15
Problem
Mc ch:
S dng cc control ca Visual Studio

Code Listing
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace Bai15_3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
MessageBoxButtons button;
MessageBoxIcon icon;
private void btnShow_Click(object sender, EventArgs e)
{
MessageBox.Show(txtMessage.Text, txtCaption.Text,button,icon);
}

52

private void Form1_Load(object sender, EventArgs e)


{
txtMessage.SelectAll();
}
private void rbnOk_CheckedChanged(object sender, EventArgs e)
{
RadioButton btn = (RadioButton)sender;
if (btn == rbnOk)
button = MessageBoxButtons.OK;
if (btn == rbnOkAndCancel)
button = MessageBoxButtons.OKCancel;
if (btn == rbnRetryAndCancel)
button = MessageBoxButtons.RetryCancel;
if (btn == rbnYesNo)
button = MessageBoxButtons.YesNo;
if (btn == rbnYesNoAndCancel)
button = MessageBoxButtons.YesNoCancel;
}
private void rbnError_CheckedChanged(object sender, EventArgs e)
{
RadioButton btn = (RadioButton)sender;
if (btn == rbnError)
icon = MessageBoxIcon.Error;
if (btn == rbnInformation)
icon = MessageBoxIcon.Information;
if (btn == rbnNone)
icon = MessageBoxIcon.None;
if (btn == rbnQuestion)
icon = MessageBoxIcon.Question;
if (btn == rbnWarming)
icon = MessageBoxIcon.Warning;
}
private void rbnLeft_CheckedChanged(object sender, EventArgs e)
{
RadioButton btn = (RadioButton)sender;
if (btn == rbnLeft)
tabControl1.Alignment = TabAlignment.Left;
if (btn == rbnBottom)
tabControl1.Alignment = TabAlignment.Bottom;
if (btn == rbnRight)
tabControl1.Alignment = TabAlignment.Right;
if (btn == rbnTop)
tabControl1.Alignment = TabAlignment.Top;
}
}
}

53

Execution Result

54

Exercise 16
Problem
Mc ch:
Xy dng h thng menu : MainMenu v ContextMenu(menu cm ng cnh) (Page
498)

Code Listing

55

Execution Result

Exercise 18
Problem
Mc ch:
Xy dng ng dng a form,
S dng form MDI

Code Listing
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace Bai18
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int i = 1;
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.Name = "Form" + i.ToString();
f.Text = "Form" + i.ToString();
f.MdiParent = this;
f.Show();
}
private void customizeToolStripMenuItem_Click(object sender, EventArgs e)
{
this.LayoutMdi(MdiLayout.TileHorizontal);
}
private void optionsToolStripMenuItem_Click(object sender, EventArgs e)
{
this.LayoutMdi(MdiLayout.TileVertical);
}
private void toolStripMenuItem1_Click(object sender, EventArgs e)
{

56

this.LayoutMdi(MdiLayout.Cascade);
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
saveFileDialog1.ShowDialog();
}

}
}

57

Execution Result

58

59

Exercise 19
Problem
Mc ch:
Xy dng ng dng kt hp i tng statusBar

Code Listing

Execution Result

Exercise 20
Problem
Mc ch:
Xy dng ng dng lin kt nhim form
Yu cu
Step by step
Creating an MDI Applicati on (Page 512)

60

Code Listing

Execution Result

Exercise 21
Problem
Mc ch:
To mt ng dng lin kt cc ng dng to ra t cc project trc.
To form khi ng (form Flash)
To form About

Code Listing

Execution Result

Exercise 22
Problem
Mc ch:
To thanh cng c (toolBar) trn ng dng

Code Listing

Execution Result

61

Module 3
Exercise 1
Problem
Thit k giao din nh hnh v

Yu cu:
Khi form thc thi
o Tt c text boxes v labels u rng.
o t focus vo text box Tn Hng v xc lp vic di chuyn Tab hp l ( menu View\Tab

Order)
o Form hin th gia mn hnh. (StartPosition =CenterScreen )
o Thit lp nt Thanh Tan nhn s kin phm Enter (AcceptButton), nt Tip nhn s kin
phm ESC (CancelButton)
o Thc hin canh l phi cho cc i tng cha d liu l s ( Text Align=Right)
X l nt lnh Thanh Tan.
o Cc text box S lng, n Gi buc phi c gi tr v ch cho php nhp s. Thm vo

:
S lng >=0. (int)
n gi >=0 (decimal)
Cung cp cc Message Box khc nhau thng bo r rng cho vic d liu b nhp sai.
o Tnh ton cho mt hng hin ti xut kt qu ra label Thnh Tin.
Nt Tip:
Thnh tin = s lng * n gi;
o Xa ni dung cc textbox v label
o t focus vo textbox u tin
Nt Kt Thc:
o Pht sinh Messagebox hi li vic ng form c chnh xc khng, nu ngi s dng xc
nhn bng nt Yes th cho that ch ng t nh

Code Listing
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace Bai01
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnThanhToan_Click(object sender, EventArgs e)
{

62

int intSoLuong;
decimal decDonGia, decThanhTien;
if (txtTenHang.Text == "")// || txtSoLuong.Text == "" || txtDonGia.Text ==
"")
{
MessageBox.Show("Chua Nhap Ten Hang");
txtTenHang.Focus();
}
else if(txtSoLuong.Text =="")
{
MessageBox.Show("Chua Nhap So Luong");
txtSoLuong.Focus();
}
else if(txtDonGia.Text =="")
{
MessageBox.Show("Chua Nhap Don Gia");
txtDonGia.Focus();
}
else
{
intSoLuong = int.Parse(txtSoLuong.Text);
decDonGia = decimal.Parse(txtDonGia.Text);
if (intSoLuong <= 0)
{
MessageBox.Show("So Luong Phai > 0");
txtSoLuong.SelectAll();
txtSoLuong.Focus();
}
else if (decDonGia <= 0)
{
MessageBox.Show("Don Gia Phai > 0");
txtDonGia.SelectAll();
txtDonGia.Focus();
}
else
{
decThanhTien = intSoLuong * decDonGia;
txtThanhTien.Text = decThanhTien.ToString();
}
}

}
private void btnTiep_Click(object sender, EventArgs e)
{
txtDonGia.Clear();
txtSoLuong.Clear();
txtTenHang.Clear();
txtThanhTien.Clear();
txtTenHang.Focus();
}
private void btnKetThuc_Click(object sender, EventArgs e)
{
if (MessageBox.Show("thoat y/n?", "thong bao", MessageBoxButtons.YesNo,
MessageBoxIcon.Question) == DialogResult.Yes)
{
this.Close();

63

}
}
private void txtSoLuong_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar >= 'A' && e.KeyChar <= 'Z') || (e.KeyChar >= 'a' &&
e.KeyChar <= 'z'))
{
e.Handled = true;
}
}

}
}

Execution Result

Exercise 2
Problem
Thit k v vit ch ng trnh tnh din tch ca hnh ch nht. Phi kim tra d liu nhp
vo t bn phm mt cch cht ch.

Code Listing
using System;
using System.Collections.Generic;

64

using
using
using
using
using
using

System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace Bai02
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void txtChieuDai_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar >= 'A' && e.KeyChar <= 'Z') || (e.KeyChar >= 'a' &&
e.KeyChar <= 'z'))
{
e.Handled = true;
}
}
private void btnThoat_Click(object sender, EventArgs e)
{
if (MessageBox.Show("thoat chuong trinh y/n?", "thong bao",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
this.Close();
}
}
private void btnTinh_Click(object sender, EventArgs e)
{
if (txtChieuDai.Text == "")
{
MessageBox.Show("Chua nhap chieu dai");
txtChieuDai.Focus();
}
else if (txtChieuRong.Text == "")
{
MessageBox.Show("chua nhap chieu rong");
txtChieuRong.Focus();
}
else
{
float fChieuRong = float.Parse(txtChieuRong.Text);
float fChieuDai = float.Parse(txtChieuDai.Text);
if (fChieuDai <= 0)
{
MessageBox.Show("Chieu dai phai > 0");
txtChieuDai.SelectAll();
txtChieuDai.Focus();
}
else if (fChieuRong <= 0)
{
MessageBox.Show("Chieu Rong Phai > 0");

65

txtChieuRong.SelectAll();
txtChieuRong.Focus();
}
else
{
float fDienTich = fChieuDai * fChieuRong;
txtDienTich.Text = fDienTich.ToString();
txtChieuDai.Focus();
}
}
}
}
}

Execution Result

Exercise 3
Problem
Thit k v vit ch ng t nh tnh chu vi ca hnh trn c bn knh R nhp vo t bn phm
(lu kim tra d liu cht ch)(Chuvi=2*pi*R). Dng hm Math.PI

Code Listing
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace Bai03
{

66

public partial class Form1 : Form


{
public Form1()
{
InitializeComponent();
}
private void txtBanKinh_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar >= 'A' && e.KeyChar <= 'Z') || (e.KeyChar >= 'a' &&
e.KeyChar <= 'z'))
{
e.Handled = true;
}
}
private void btnThoat_Click(object sender, EventArgs e)
{
if (MessageBox.Show("thoat chuong trinh y/n?", "thong bao",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
this.Close();
}
}
private void btnTinh_Click(object sender, EventArgs e)
{
double fBanKinh;
if (txtBanKinh.Text == "")
{
MessageBox.Show("Chua Nhap Ban Kinh");
txtBanKinh.Focus();
}
else
{
fBanKinh = double.Parse(txtBanKinh.Text);
if (fBanKinh <= 0)
{
MessageBox.Show("Ban Kinh Phai > 0");
txtBanKinh.SelectAll();
txtBanKinh.Focus();
}
else
{
double fChuVi = 2 * Math.PI * fBanKinh;
txtChuVi.Text = fChuVi.ToString();
txtBanKinh.SelectAll();
}
}
}
}
}

Execution Result

67

Exercise 4
Problem
Thit k v x l ch ng t nh gii ph ng t nh bc 1, 2.

Code Listing
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace Bai04
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void txtC_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar >= 'A' && e.KeyChar <= 'Z') || (e.KeyChar >= 'a' &&
e.KeyChar <= 'z'))
{
e.Handled = true;
}
}
private void btnThoat_Click(object sender, EventArgs e)
{
if (MessageBox.Show("thoat chuong trinh y/n?", "thong bao",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
this.Close();
}
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked == true)
txtC.Enabled = false;

68

else
txtC.Enabled = true;
}
public bool KiemTraTextbox(TextBox t)
{
if (t.Text == "")
{
MessageBox.Show("chua nhap a,b,c");
t.Focus();
return false;
}
return true;
}
//ax + b =0
public void GiaiPTbac1(double a, double b)
{
if (a == 0)
{
if (b == 0)
{
txtX.Text = "phuong trinh vo nghiem";
}
else
{
txtX.Text = "phuong trinh vo so nghiem";
}
}
else
{
double x = -b / a;
txtX.Text = "x = "+x.ToString();
}
}
//ax*x+bx+c=0
public void GiaiPTbac2(double a, double b, double c)
{
if (a == 0)
{
GiaiPTbac1(b, c);
}
else
{
double delta = b * b - 4 * a * c;
if (delta < 0)
{
txtX.Text = "phuong trinh vo nghiem";
}
else if (delta == 0)
{
double x = -b / (2 * a);
txtX.Text = "x = " + x.ToString();
}
else
{
double x1 = (-b - Math.Sqrt(delta))/(2*a);
double x2 = (-b + Math.Sqrt(delta)) / (2 * a);

69

txtX.Text = "x1 = " + x1.ToString() + " ,x2= " + x2.ToString();


}
}
}
private void btnGiai_Click(object sender, EventArgs e)
{
double a, b, c;
if (checkBox1.Checked == false)
{
if (KiemTraTextbox(txtA) == true)
{
if (KiemTraTextbox(txtB) == true)
{
if (KiemTraTextbox(txtC) == true)
{
a = double.Parse(txtA.Text);
b = double.Parse(txtB.Text);
c = double.Parse(txtC.Text);
GiaiPTbac2(a, b, c);
}
}
}
}
else
{
if (KiemTraTextbox(txtA) == true)
{
if (KiemTraTextbox(txtB) == true)
{
a = double.Parse(txtA.Text);
b = double.Parse(txtB.Text);
GiaiPTbac1(a, b);
}
}
}
}
}
}

70

Execution Result

Exercise 5
Problem
Mc ch:
S dng hng s, bin ton cc (modul e variable)
Yu cu:
1) Sinh vin t thit k cc i tng trn form cho ph hp
2) Thit t TabIndex cho hp l.
3) Nhn nt Tnh hoc Enter th tnh v hin thng tin ln cc t ng ng.
4) Nhn vo Exit hoc Esc th thot ch n g trnh.
Ghi ch: s dng bin ton cc v hng s cho hp l

Code Listing
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace Bai05
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void txtSoLuong_KeyPress(object sender, KeyPressEventArgs e)

71

{
if((e.KeyChar >= 'A' && e.KeyChar <= 'Z')||(e.KeyChar >= 'a'
&&e.KeyChar<='z'))
{
e.Handled=true;
}
}
int intTongSoLuong = 0, intTongTien = 0, intSoLanBan=0;
float fTrungBinh;
private void btnTinh_Click(object sender, EventArgs e)
{
int intSoLuong,intDonGia,intThanhTien;
if (txtSoLuong.Text == "")
{
MessageBox.Show("chua nhap so luong");
txtSoLuong.Focus();
}
else if (txtDonGia.Text == "")
{
MessageBox.Show("chua nhap don gia");
txtDonGia.Focus();
}
else
{
intSoLuong = int.Parse(txtSoLuong.Text);
intDonGia = int.Parse(txtDonGia.Text);
if (intSoLuong <= 0)
{
MessageBox.Show("so luong fai > 0");
txtSoLuong.SelectAll();
txtSoLuong.Focus();
}
else if (intDonGia <= 0)
{
MessageBox.Show("don gia fai > 0");
txtDonGia.SelectAll();
txtDonGia.Focus();
}
else
{
//tinh thanh tien
intThanhTien = intDonGia * intSoLuong;
txtThanhTien.Text = intThanhTien.ToString();
//tinh tong so luong
intTongSoLuong += intSoLuong;
txtTongSoLuong.Text = intTongSoLuong.ToString();
//tinh tong tien
intTongTien += intThanhTien;
txtTongTien.Text = intTongTien.ToString();
//tinh trung binh tren moi lan ban
intSoLanBan++;
fTrungBinh = (float)intTongTien / intSoLanBan;
txtTrungBinh.Text = fTrungBinh.ToString();
}
}

72

}
private void btnBanMoi_Click(object sender, EventArgs e)
{
intTongSoLuong = 0;
intTongTien = 0;
intSoLanBan = 0;
Refresh();
}
public void Refresh()
{
txtDonGia.Clear();
txtSoLuong.Clear();
txtThanhTien.Clear();
txtTongSoLuong.Clear();
txtTongTien.Clear();
txtTrungBinh.Clear();
}
private void btnThoat_Click(object sender, EventArgs e)
{
if (MessageBox.Show("thoat chuong trinh y/n?", "thong bao",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
this.Close();
}
}
}
}

73

Execution Result

74

Exercise 6
Problem
Mc ch:
S dng hng s, bin ton cc (module variable)
1. Khi ch ng trnh va thc thi:
- Form c hin th gia mn hnh. Canh l phi cho cc control cha d liu l s, thit
lp h thng Tab hp l.
- Thit lp nt Tnh TT nhn phm Enter thay cho s kin Click.
2. Yu cu ci t
Tn KHch hng khng c php rng.
S lng sch l s nguyn d ng
Mi quyn sch u c bn vi gi l 20000.
- Nt Tnh TT: tnh thnh tin v xut kt qu ln lable Thnh tin
Thnh tin = S lng * n Gi ;
Lu : Nu Khch hng l SV th c gim 5% thnh tin.
- Nt Tip:
- Xa ni dung cc control trong gourpbox Ha n
- t focus cho Textbox Tn Khch Hng
- Nt Thng K: Tnh v hin th kt qu trn cc lable trong groupbox Thng k
- Nt Kt Thc: Pht sinh messageBox hi li ngi dng c tht s mun ng ng
dng hay khng?

Code Listing
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace Bai06
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int dongia = 20000;
private void Form1_Load(object sender, EventArgs e)
{
}
private void txtSLSach_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar >= 'A' && e.KeyChar <= 'Z') || (e.KeyChar >= 'a' &&
e.KeyChar <= 'z'))

75

{
e.Handled = true;
}
}
private void btnKetThuc_Click(object sender, EventArgs e)
{
if (MessageBox.Show("thoat chuong trinh y/n?", "thong bao",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
this.Close();
}
}
private void btnTiep_Click(object sender, EventArgs e)
{
txtTenKH.Clear();
txtSLSach.Clear();
txtThanhTien.Clear();
lblTongDoanhThu.Text = "";
lblTongSoKH.Text = "";
lblTongSoKHLaSV.Text = "";
fTongDoanhThu = 0;
intTongKH = 0;
intTongSV = 0;
checkBox1.Checked = false;
}
float fTongDoanhThu = 0; int intTongKH = 0,intTongSV = 0;
private void btnTinhTT_Click(object sender, EventArgs e)
{
int intSoLuong;
float fThanhTien,fHeSo;
if (txtTenKH.Text == "")
{
MessageBox.Show("Ten khach hang ko dc rong");
txtTenKH.Focus();
}
else
{
intSoLuong = int.Parse(txtSLSach.Text);
if (intSoLuong <= 0)
{
MessageBox.Show("So Luong fai > 0");
txtSLSach.SelectAll();
txtSLSach.Focus();
}
else
{
if (checkBox1.Checked == true)
{
fHeSo = 0.95f;
intTongKH++;
intTongSV++;
}
else
{
intTongKH++;
fHeSo = 1;
}
//tinh thanh tien

76

fThanhTien = intSoLuong * dongia * fHeSo;


txtThanhTien.Text = fThanhTien.ToString();

fTongDoanhThu += fThanhTien;
}
}
}
private void btnThongKe_Click(object sender, EventArgs e)
{
//tinh tong so khach hang
lblTongSoKH.Text = intTongKH.ToString();
//tinh tong so khach hang la sv
lblTongSoKHLaSV.Text = intTongSV.ToString();
//tinh tong doanh thu
lblTongDoanhThu.Text = fTongDoanhThu.ToString();
}
}
}

77

Execution Result

78

Exercise 7
Problem
Vit ch ng t nh nhp vo n m d ng lch v xut n m m lch t ng ng.
Bit rng : N m m = Can + Chi;
Can = N m d ng % 10 :
Chi = d ng lch % 12 :

Code Listing
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

79

namespace Bai07
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void txtNamDuongLich_KeyPress(object sender, KeyPressEventArgs e)
{
if ((e.KeyChar >= 'A' && e.KeyChar <= 'Z') || (e.KeyChar >= 'a' &&
e.KeyChar <= 'z'))
{
e.Handled = true;
}
}
private void btnDoi_Click(object sender, EventArgs e)
{
int namDuongLich,intCan,intChi;
string namAmLich = "";
string[] strCan = { "Canh", "Tn", "Nhm", "Qu", "Gip", "t", "Bnh",
"inh", "Mu", "K" };
string[] strChi = { "Thn", "Du", "Tut", "Hi", "T", "Su", "Dn",
"Mo", "Thn", "T", "Ng", "Mi" };
if (txtNamDuongLich.Text != "")
{
namDuongLich = int.Parse(txtNamDuongLich.Text);
if (namDuongLich <= 0)
{
MessageBox.Show("Nam Duong Lich Phai > 0");
txtNamDuongLich.SelectAll();
txtNamDuongLich.Focus();
}
else
{
intCan = namDuongLich % 10;
intChi = namDuongLich % 12;
namAmLich = strCan[intCan].ToString() + " " +
strChi[intChi].ToString();
txtNamAmLich.Text = namAmLich.ToString();
txtNamDuongLich.SelectAll();
}
}
else
{
MessageBox.Show("chua nhap nam duong lich");
txtNamDuongLich.Focus();
}
}
}
}

80

Execution Result

Exercise 8
Problem
Ch ng trnh quay s may mn
Thit k giao din nh hnh
- Groupbox cha 3 label.
- 2 Label dng hin th kt qu (canh l pi)
- 3 button nh hnh v.
Yu cu
Khi chng trnh va bt u
- 3 label s hin th 3 s 7.
- My tnh c 100 ng
- Ngi ch i c 100 ng
Khi Click nt quay s
Lut ch i:
Mi ln quay s, ngi ch i phi tr trc 30 ng, t ng ng l my s c cng thm
30 ng. V nu ngi ch i c s tin t h n 30 ng th s khng c php ch i tip
Nu mi ln quay c s 7, ngi ch i s c thng nh sau
- Nu u tin l s 7 (random t 0 n 8), c thng 100 ng + 50% s tin ca
my.
- Nu s 2 l s 7(random t 0 n 9), ngi ch i c thng 30 ng + 50% tin ca
my.
- Nu s 3 l s 7(random t 0 n 10), ngi ch i c thng 10 ng;
(s tin ngi ch i s c cng dn nu c 3 cng l s 7, tin my s gim i phn
tr m t ng ng)
Nt game mi
Cho php 1 lc ch i mi han tan (set li tin ng i ch i v tin my l 100)

Code Listing
using System;
using System.Collections.Generic;
using System.ComponentModel;

81

using
using
using
using
using

System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace Bai08
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int tienNguoiChoi, tienMay = 100, soThu1, soThu2, soThu3, tienThuong;
private void btnQuaySo_Click(object sender, EventArgs e)
{
tienNguoiChoi = int.Parse(lblTienNguoiChoi.Text);
tienNguoiChoi -= 30;
lblTienNguoiChoi.Text = tienNguoiChoi.ToString();
timer1.Interval = 100;
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
btnQuaySo.Enabled = false;
if (timer1.Interval < 200)
{
Random r = new Random();
soThu1 = r.Next(1, 9);
soThu2 = r.Next(1, 8);
soThu3 = r.Next(1, 7);
lblNo1.Text = soThu1.ToString();
lblNo2.Text = soThu2.ToString();
lblNo3.Text = soThu3.ToString();
timer1.Interval += 5;
}
else
{
timer1.Stop();
tienThuong = 0;
if (soThu1 == 7)
{
tienThuong += 100 + tienMay / 2;
tienMay /= 2;
lblTienMay.Text = tienMay.ToString();
}

if (soThu2 == 7)
{
tienThuong += 30 + tienMay / 2;
tienMay /= 2;

82

lblTienMay.Text = tienMay.ToString();
}
if (soThu3 == 7)
tienThuong += 10;
tienNguoiChoi += tienThuong;
lblTienNguoiChoi.Text = tienNguoiChoi.ToString();
MessageBox.Show("Thuong " + tienThuong + " dong!");
if (tienNguoiChoi >= 30)
btnQuaySo.Enabled = true;
else
{
btnGameMoi.Enabled = true;
}
}

}
private void btnGameMoi_Click(object sender, EventArgs e)
{
tienMay = 100;
tienNguoiChoi = 100;
lblTienMay.Text = tienMay.ToString();
lblTienNguoiChoi.Text = tienNguoiChoi.ToString();
btnQuaySo.Enabled = true;
}

private void Form1_Load(object sender, EventArgs e)


{
btnGameMoi.Enabled = false;
}
private void btnKetThuc_Click(object sender, EventArgs e)
{
this.Close();
}

}
}

Execution Result

83

84

Exercise 9
Problem
Vit ch n g trnh cho php pht sinh 1 s nguyn thu c [0,9] , sau cho ngi dng
on s v ch ng trnh s hin kt qu xem ngi dng c on ng s pht sinh hay
khng.
HD: Dng lp Random pht sinh s ngu nhin.

Code Listing
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

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

private
private
private
{
r =

int soDung,soDoan;
Random r;
void Form1_Load(object sender, EventArgs e)
new Random();

85

soDung = r.Next(0, 9);


}

private void btnDoan_Click(object sender, EventArgs e)


{
soDoan = int.Parse(txtNhap.Text);
if(soDoan < soDung)
{
MessageBox.Show("can doan so lon hon");
}
else
{
if(soDoan > soDung)
{
MessageBox.Show("can doan so nho hon");
}
else
{
MessageBox.Show("chuc mung ban da doan dung,moi doan tiep");
soDung = r.Next(0, 9);
}
}
txtNhap.SelectAll();
txtNhap.Focus();
}
private void btnThoat_Click(object sender, EventArgs e)
{
Close();
}
}
}

Execution Result

86

Exercise 10
Problem
Thit k giao din trnh by s cc ch ngi ca mt rp chiu phim gip ngi s dng
chn v tr mun mua. Trn s ny cng th hin nhng v tr bn v v nhng v tr
cha bn v bng cch th hin mu khc nhau ( gh cha bn v mu trng, gh bn
v mu vng, gh ang chn mu xanh).
Khi khi ng, ng dng phi nm gia mn hnh. Khng cho php ngi dng thay i
kch thc form. Khi ngi s dng nhp chut ti mt v tr trn s th:
o Nu y l v tr cha bn v th i mu ca v tr ny sang mu xanh cho bit y l
v tr ang chn.
o Nu y l v tr ang chn (c mu xanh) th i mu ca v tr ny tr v mu trng
o Nu y l mt v tr bn v th xut hin mt thng bo cho ngi s dng bit thng
qua messageBox.
Sau khi chn cc v tr ngi s sng c th nhn vo nt CHN hoc HY B.
u click vo nt CHN (hoc nhn phm Enter) th:
i mu cc v tr chn (mu xanh) trn s sang mu vng (cho bit v tr bn v)
v xut ln label thnh tin phi tr cho s v mua ( gi s gi v l 100/gh)
u click vo nt HY B (hoc nhn phn ESC) th:
i mu cc v tr chn (mu xanh) trn s sang mu trng tr li v xut ln label
thnh tin gi tr 0

Code Listing
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

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

87

private void btnKetThuc_Click(object sender, EventArgs e)


{
if (MessageBox.Show("thoat chuong trinh y/n?", "thong bao",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
this.Close();
}
}
List<Label> DanhSachChon = new List<Label>();
int intThanhTien = 0;
private void label2_Click(object sender, EventArgs e)
{
Label lbl = (Label)sender;
//neu label khac mau vang
if (lbl.BackColor != Color.Yellow)
{
//neu label la mau trang
if (lbl.BackColor == Color.White)
{
//chuyen label mau trang thanh mau xanh
lbl.BackColor = Color.Blue;
DanhSachChon.Add(lbl);
}
else//nguoc lai label mau xanh
{
//chuyen sang mau trang
lbl.BackColor = Color.White;
DanhSachChon.Remove(lbl);
}
}
else//label mau vang
{
//thang bao co nguoi chon roi
MessageBox.Show("Bn ny c ngi chn ri");
}
}
private void btnChon_Click(object sender, EventArgs e)
{
foreach (Label l in DanhSachChon)
{
l.BackColor = Color.Yellow;
intThanhTien += 100;
}
lblThanhTien.Text = intThanhTien.ToString();
intThanhTien = 0;
DanhSachChon = new List<Label>();
}
private void btnHuy_Click(object sender, EventArgs e)
{
foreach (Label l in DanhSachChon)
{
l.BackColor = Color.White;
}
lblThanhTien.Text = "";
DanhSachChon = new List<Label>();
}

88

}
}

Execution Result

89

Exercise 11
Problem
H y to mt Project dng qun l gi thu my ca mt phng my c giao din
v yu cu nh sau:
o Khi form va load ln mn hnh th
cc CheckBox Bt u c Enabled=True
cc CheckBox Kt thc c Enabled=False
Cc Label c Caption= rng
90

o Khi ngi s dng Click vo ChechBox Bt u ca mt my v nu thuc tnh


value ca n =1 th:
Hin Gi hin ti ln Label bt u ca my t ng ng
Cho thuc tnh Enabled ca CheckBox Bt u =False
Cho thuc tnh Enabled ca CheckBox Kt thc =True
o Khi ngi s dng Click vo ChechBox Kt thc ca mt my v nu thuc tnh
value ca n =1 th:
Hin Gi hin ti ln Label Kt thc ca my t ng ng
Da vo Gi v Pht (khng cn quan tm n s giy) trn cc label Bt
u v Kt thc tnh ra s tin phi tr, ri dng Msgbox thng bo cho ngi
s dng nh hnh bn (tin thu my l 3000/gi)
Xa ni dung trong cc Label Bt u v Kt thc
Cho thuc tnh Enabled ca CheckBox Bt u =True
Cho thuc tnh Enabled ca CheckBox Kt t hc =False
Cho thuc tnh Value ca CheckBox Bt u =0
Cho thuc tnh Value ca CheckBox Kt thc =0
Khi ngi s dng Click vo nt Dng chng trnh th kim tra nu c my ang
thu phi nhc nh ngi s dng bng MsgBox, khi no ngi s dng tht s
mun kt thc th mi dng ch ng trnh.

Code Listing

Execution Result

Exercise 12
Problem
H y to mt Project dng qun l gi thu my ca mt phng my c giao din
v yu cu nh sau:
o Khi form va load ln mn hnh th
Cc image trong khung my 1 v my 2 c picture l My tnh
Cc Label c Text = rng
o Khi ngi s dng click vo image ca my 1 hoc my 2 th:
Nu l my cha thu:
i picture ca image thnh hnh ng h
Hin gi hin ti vo label bt u ca my (label pha trn)
91

Nu l my ang thu:
Hin gi hin ti vo label Kt thc ca my (label pha di)
Da vo Gi v Pht (khng cn quan tm n s giy) trn cc label Bt
u v Kt thc tnh ra s tin phi tr, ri dng Msgbox thng bo (tin thu
my l 3000/gi)
i picture ca image thnh hnh My tnh
Xa ni dung trong cc Label Bt u v Kt thc Khi ngi s dng Click
vo nt Kt thc th kim tra nu c my ang thu phi nhc nh ngi s dng
bng MsgBox, khi no ngi s dng tht s mun kt thc th mi dng ch ng
trnh.

Code Listing

Execution Result

Module 4
Exercise 1
Problem
Mc ch:
S dng lp Exception by li ch ng trnh.
S dng MessageBox hin th thng bo li
Yu cu:
Vit ch ng trnh tnh s nhin liu tiu th trung bnh theo giao din sau
Phi bt li chc ch cc trng hp sau:
- S dm ng, s gallon tiu th l s d ng.
- Li trn s
- Li chia cho s 0
-

Code Listing
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;

92

using
using
using
using

System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace Bai01
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
int miles, galon;
private void btnCalculate_Click(object sender, EventArgs e)
{
miles = int.Parse(txtMilesDriven.Text);
galon = int.Parse(txtGallonsOfGasUsed.Text);
lblEfficiency.Text = ((float)miles / galon).ToString();
}
private void txtMilesDriven_Validating(object sender, CancelEventArgs e)
{
//kiem tra nhap du lieu vao textbox
TextBox txt = (TextBox)sender;
try
{
//1. neu textbox rng
if (txt.Text == "")
{
//thong bao chua nhap du lieu
errorProvider1.SetError(txt, "chua nhap du lieu");
//giu con tro
e.Cancel = true;
}
else//2. da nhap du lieu
{
try
{
//2.2 tao bien tam x va kiem tra
int x = int.Parse(txt.Text);
//3. so nho hon 0
if (x < 0)
{
throw new ArithmeticException();
}
else//4. du lieu nhap > 0
{
errorProvider1.SetError(txt, "");
}
}
//trn s
catch (OverflowException)
{
errorProvider1.SetError(txt, "so lon wa");
e.Cancel = true;
}
}

93

}
//2.1 du lieu ko phai la s
catch (FormatException)
{
//2.1.1 thong bao
errorProvider1.SetError(txt, "nhap so nguyen");
//2.1.2 giu con tro
e.Cancel = true;
}
//3.1 bat su kien so nho hon 0
catch (ArithmeticException)
{
//3.1.1 thong bao
errorProvider1.SetError(txt, "so phai >0");
//3.1.2 giu con tro
e.Cancel = true;
}
//5. cac truong hop loi khac
catch (Exception ex)
{
errorProvider1.SetError(txt, ex.Message.ToString());
e.Cancel = true;
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("thoat y/n?", "thong bao 22222",
MessageBoxButtons.YesNo) == DialogResult.Yes)
{
e.Cancel = false;
}
else
{
e.Cancel = true;
}
}
private void button1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

94

Execution Result

95

96

Exercise 2
Problem
Mc ch:
S dng lp Exception by li ch ng trnh.
S dng MessageBox hin th thng bo li
Yu cu:
Vit li bi 1, nhng s dng i tng ErrorProvider hin th cc thng bo li ngay
trn control

Code Listing

Execution Result

Exercise 3
Problem
Mc ch:
S dng lp Exception by li ch ng t nh.
S dng finally Block
Lu :
Ch ng t nh phi thc hin vic ng file bt k c xy ra li hay khng.

Code Listing

97

Execution Result

Exercise 4
Problem
Mc ch:
S dng Component ErrorProvider kt hp k thut Validation trn cc control
Yu cu:
Vit li bi tp mt nhng s dng chn li ngi dng bng k thut Validation.

Code Listing

Execution Result

Exercise 5
Problem
Mc ch:
Lp trnh vi lp Exception thuc khng gian System.IO.IOException
S dng cc component OpenFileDialog, SaveFileDialog, ColorDialog, and FontDialog.

Code Listing

Execution Result

98

Exercise 6
Problem
Mc ch:
S dng k thut Validating User Input.
Yu cu:
Thit k form login nh hnh bn di.
Xut thng bo login hp l nu ni dung ca 2 textbox UserName v Password l khc
rng v khng c bt k khang trng no bn trong. Ngc li xut thng bo li c th
thng qua ErrorProvider.
Cho php ngi dng ng Form bng nt Cancle ngay c khi xy ra li trn bt k
trng d liu no.

Code Listing

Execution Result

Module 5
Exercise 1
Problem
Mc ch:
Xy dng mng mt chiu trn ConsoleApp
Yu cu:
Nhp mt mng 1 chiu c N phn t (N<20) (cc gi tr c pht sinh ngu nhin trong [
100, 100])
a. Tm s ln nht, nh nht trong mng. Xut ra v tr cc gi tr ny.
b. m xem trong mng c bao nhiu s d ng, bao nhiu s m, bao nhiu s 0.
c. Nhp vo s nguyn x, kim tra xem x c trong mng hay khng.
d. Tm s d ng nh nht trong mng, s m ln nht trong mng
e. In d y gim dn.

Code Listing

99

Execution Result

Exercise 2
Problem
Mc ch:
Xy dng mng mt chiu trn ConsoleApp
Yu cu:
Nhp mt mng 2 chiu c N x N phn t (N<20) (cc gi tr c pht sinh ngu nhin
trong [-100,100])
a. Tm s ln nht, nh nht trong mng. Xut ra v tr cc gi tr ny.
b. m xem trong mng c bao nhiu s d ng, bao nhiu s m, bao nhiu s 0.
c. m s d ng, s m, s 0 di ng cho chnh, cho ph.
d. Tnh tng cc phn t trong ng cho chnh, cho ph.
e. Tnh tng cc phn t nm bn di ng cho chnh, cho ph.
f. Tm s ln nht trong tng dng ca mng.

Code Listing

Execution Result

Exercise 3
Problem
Mc ch:
S dng mng mt chiu
Yu cu:
Thit k Form nh hnh sau:

Code Listing
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;

100

using
using
using
using

System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace Bai03
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//khai bao
private const int Max_Size = 10;
private int[] intArray;
//form load
private void Form1_Load(object sender, EventArgs e)
{
intArray = new int[Max_Size];
}

public void TaoMangNgauNhien()


{
Random r = new Random();
for(int i = 0; i< intArray.Length;i++)
{
intArray[i] = r.Next(1, 101);
}
}
public void XuatMang(int[] a)
{
for (int i = 0; i < a.Length; i++)
{
txtMangGoc.Text += " " + a[i].ToString();
}
}
public int TongMang(int[] a)
{
int kq = 0;
for (int i = 0; i < a.Length; i++)
{
kq += a[i];
}
return kq;
}
public int FindMin(int[] a)
{
int min = a[0];
for (int i = 1; i < a.Length; i++)
{
if(a[i]<min)
{

101

min = a[i];
}
}
return min;
}
public void TangMoiPhanTuMangLen2(int[] a)
{
txtKetQua.Clear();
for (int i = 0; i < a.Length; i++)
{
a[i] += 2;
txtKetQua.Text += " " + a[i].ToString();
}
}
public int SoPhanTuLe(int[] a)
{
int dem = 0;
for (int i = 0; i < a.Length; i++)
{
if(a[i]%2==1)
{
dem++;
}
}
return dem;
}
public int TongPhanTuLe(int[] a)
{
int tongle = 0;
for (int i = 0; i < a.Length; i++)
{
if (a[i] % 2 == 1)
{
tongle+= a[i];
}
}
return tongle;
}
public void SapMangTang(int[] a)
{
for (int i = 0; i < a.Length-1; i++)
{
for(int j = i+1;j<a.Length;j++)
{
if(a[i]>a[j])
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
public void SapMangGiam(int[] a)
{

102

for (int i = 0; i < a.Length - 1; i++)


{
for (int j = i + 1; j < a.Length; j++)
{
if (a[i] < a[j])
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
private void btnXuatMangNgauNhien_Click(object sender, EventArgs e)
{
TaoMangNgauNhien();
XuatMang(intArray);
}
private void btnTimPTNhoNhat_Click(object sender, EventArgs e)
{
txtKetQua.Text = FindMin(intArray).ToString();
}
private void btnTinhTongGiaTriMang_Click(object sender, EventArgs e)
{
txtKetQua.Text = TongMang(intArray).ToString();
}
private void btnTangMoiPTLen2_Click(object sender, EventArgs e)
{
TangMoiPhanTuMangLen2(intArray);
}
private void btnDemSoPTLe_Click(object sender, EventArgs e)
{
txtKetQua.Text = SoPhanTuLe(intArray).ToString();
}

private void btnTongGiaTriPTLe_Click(object sender, EventArgs e)


{
txtKetQua.Text = TongPhanTuLe(intArray).ToString();
}
private void btnSapMangTang_Click(object sender, EventArgs e)
{
SapMangTang(intArray);
HienThiMang(intArray);
}
public void HienThiMang(int[] a)
{
txtKetQua.Clear();
for (int i = 0; i < a.Length; i++)
{
txtKetQua.Text += " " + a[i].ToString();
}
}

103

private void btnSapMangGiam_Click(object sender, EventArgs e)


{
SapMangGiam(intArray);
HienThiMang(intArray);
}

}
}

Execution Result

104

105

106

Exercise 4
Problem
Mc ch:
S dng mng hai chiu trn ConsoleApp
Yu cu:

107

Nhp mt mng 2 chiu c N x N phn t (N<20) (cc gi tr c pht sinh ngu nhin
trong [-100,100]). Tm s d ng nh nht trong mng.
V d:
-9
8
3
-3
5
0
1
-30
7
S d ng nh nht trong mng l 1

Code Listing

Execution Result

Exercise 5
Problem
Mc ch:
S dng Arraylist,
Yu cu:

Xy dng t in n gin
- Khi nhp vo combobox 1 t cn tra th ch ng trnh s d tm n ch no khp vi k
t gn nht
- Khi nhn nt Enter hoc Doubleclick vo t cn tra th ngha t ng ng ca t s hin th
vo textbox bn phi t ng ng.
- Danh sch cc t lu s

Code Listing
using
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;
System.Collections;

namespace Bai06
{

108

public partial class Form1 : Form


{
public Form1()
{
InitializeComponent();
}
private ArrayList arr;
private void Form1_Load(object sender, EventArgs e)
{
arr = new ArrayList();
ThemDuLieuVaoArray();
HienThiArrLenListview();
txtSearch.Focus();
}
void ThemDuLieuVaoArray()
{
arr.Add("student");
arr.Add("Sinh Vin,Hc Sinh");
arr.Add("teacher");
arr.Add("Gio Vin,Ging Vin");
arr.Add("worker");
arr.Add("Cng Nhn");
arr.Add("mouse");
arr.Add("Con Chut");
arr.Add("stupid");
arr.Add("Ngu Ngc");
}
void HienThiArrLenListview()
{
for (int i = 0; i < arr.Count; i = i + 2)
{
listBox1.Items.Add(arr[i].ToString());
}
}

private void btnThoat_Click(object sender, EventArgs e)


{
this.Close();
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
txtTiengAnh.Text = listBox1.SelectedItem.ToString();
for (int i = 0; i < arr.Count; i = i + 2)
{
if (arr[i].Equals(listBox1.SelectedItems[0].ToString()))
{
richTextBox1.Text = arr[i + 1].ToString();
}

109

}
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
for (int i = 0; i < arr.Count; i = i + 2)
{
int x = txtSearch.Text.Length;
if (arr[i].ToString().Substring(0, x).Equals(txtSearch.Text))
{
int y = arr[i].ToString().Length;
txtTiengAnh.Text = arr[i].ToString();
richTextBox1.Text = arr[i + 1].ToString();
//txtTiengAnh.Select(x, y - x);
break;
}
}
}
}
}

110

Execution Result

111

Module 6
Exercise 1
Problem
Yu cu:
Thit k class Ha n p ng yu cu x l ca giao din trn.

Code Listing
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Text;

namespace Bai01
{
class HoaDon
{
private String tenhang;
private double soluong;
private double dongia;

112

public static double sohoadon = 0;


public static double doanhthu = 0;
public string Tenhang
{
get { return tenhang; }
set { tenhang = value; }
}
public double Soluong
{
get { return soluong; }
set { soluong = value; }
}
public double Dongia
{
get { return dongia; }
set { dongia = value; }
}
public static double Sohoadon
{
get { return sohoadon; }
}
public static double Doanhthu
{
get { return doanhthu; }
}
public HoaDon()
{
sohoadon = 0;
doanhthu = 0;
}
public HoaDon(String tenhang,double soluong,double dongia)
{
this.tenhang = tenhang;
this.soluong = soluong;
this.dongia = dongia;
sohoadon++;
}
public double thanhTien()
{
double thanhTien = this.soluong*this.dongia;
doanhthu += thanhTien;
return thanhTien;
}
public double getSoHoaDon()
{
return sohoadon;
}
public double getDoanhThu()
{
return doanhthu;

113

}
}
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace Bai01
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private double soLuong, donGia;
private HoaDon h;
bool kiemTraTenHang()
{
if (string.IsNullOrEmpty(txtTenHang.Text))
{
MessageBox.Show("cha nhp tn hng");
txtTenHang.Focus();
return false;
}
return true;
}
bool kiemTraSoLuong()
{
try
{
if (string.IsNullOrEmpty(txtSoLuong.Text))
{
MessageBox.Show("cha nhp s lng");
txtSoLuong.Focus();
return false;
}
else
{
soLuong = double.Parse(txtSoLuong.Text);
if (soLuong <= 0) throw new Exception();
}
}
catch (Exception)
{
MessageBox.Show("S Lng Khng Hp L");
txtSoLuong.SelectAll();
txtSoLuong.Focus();
return false;
}
return true;

114

}
bool kiemTraDonGia()
{
try
{
if (string.IsNullOrEmpty(txtDonGia.Text))
{
MessageBox.Show("cha nhp n Gi");
txtDonGia.Focus();
return false;
}
else
{
donGia = double.Parse(txtDonGia.Text);
if (donGia <= 0) throw new Exception();
}
}
catch (Exception)
{
MessageBox.Show("n Gi Khng Hp L");
txtDonGia.SelectAll();
txtDonGia.Focus();
return false;
}
return true;
}
private void btnTinh_Click(object sender, EventArgs e)
{
if(kiemTraTenHang())
{
if(kiemTraSoLuong())
{
if(kiemTraDonGia())
{
h = new HoaDon(txtTenHang.Text, soLuong, donGia);
txtThanhTien.Text = h.thanhTien().ToString();
}
}
}
}
private void btnTiep_Click(object sender, EventArgs e)
{
txtTenHang.Clear();
txtSoLuong.Clear();
txtDonGia.Clear();
txtThanhTien.Clear();
txtTenHang.Focus();
}
private void btnThongKe_Click(object sender, EventArgs e)
{
txtSoHoaDon.Text = h.getSoHoaDon().ToString();
txtTongDoanhThu.Text = h.getDoanhThu().ToString();
}
private void btnKetThuc_Click(object sender, EventArgs e)
{

115

this.Close();
}
}
}

116

Execution Result

117

Exercise 2
Problem
Yu cu:
1. Thit k Form nh hnh sau:
2. Thit k class Ha n p ng yu cu x l ca giao din trn.

Code Listing
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Text;

namespace Bai02
{
class HoaDon
{
//properties
private String hoten;
private String diachi;
private String dienthoai;
private double giatien;
private double thue;
private bool muaxeden;
private static double sokhachhang=0;
private static double sokhachmuaxeden=0;
private static double doanhthu=0;
//get , set
public string Hoten
{
get { return hoten; }
set { hoten = value; }
}
public string Diachi
{
get { return diachi; }
set { diachi = value; }
}
public string Dienthoai
{
get { return dienthoai; }
set { dienthoai = value; }
}
public static double Sokhachhang
{
get { return sokhachhang; }
}
public static double Sokhachmuaxeden
{
get { return sokhachmuaxeden; }
}

118

public static double Doanhthu


{
get { return doanhthu; }
}
public double Giatien
{
get { return giatien; }
set { giatien = value; }
}
public double Thue
{
get { return giatien*0.1; }
set { thue = value; }
}
//constructors
public HoaDon()
{
sokhachhang = 0;
sokhachmuaxeden = 0;
doanhthu = 0;
}
public HoaDon(string hoten, string diachi, string dienthoai, double giatien,
bool muaxeden)
{
this.hoten = hoten;
this.dienthoai = dienthoai;
this.diachi = diachi;
this.giatien = giatien;
this.muaxeden = muaxeden;
sokhachhang++;
if (muaxeden) sokhachmuaxeden++;
}
public double phuThu()
{
if(muaxeden)
{
return giatien*0.05;
}
return 0;
}
public double TinhThanhTien()
{
double thanhTien = this.phuThu() + this.Giatien + this.Thue;
doanhthu += thanhTien;
return thanhTien;
}
public double getTongKH()
{
return sokhachhang;
}
public double getKhMuaXeDen()
{

119

return sokhachmuaxeden;
}
public double TongDoanhThu()
{
return doanhthu;
}
}
}
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace Bai02
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private HoaDon hd;
private void btnTinh_Click(object sender, EventArgs e)
{
bool muaxeden = rbnMauDen.Checked;
hd = new
HoaDon(txtHoTen.Text,txtDiaChi.Text,txtDienThoai.Text,double.Parse(txtGiaTien.Text),mu
axeden);
txtPhuThu.Text = hd.phuThu().ToString();
txtThue.Text = hd.Thue.ToString();
txtThanhTien.Text = hd.TinhThanhTien().ToString();
}
private void btnTiep_Click(object sender, EventArgs e)
{
txtHoTen.Clear();
txtDiaChi.Clear();
txtDienThoai.Clear();
txtGiaTien.Clear();
txtPhuThu.Clear();
txtThue.Clear();
txtThanhTien.Clear();
}
private void btnThongKe_Click(object sender, EventArgs e)
{
txtTongKH.Text = hd.getTongKH().ToString();
txtTongKHMuaXeDen.Text = hd.getKhMuaXeDen().ToString();
txtTongDoanhThu.Text = hd.TongDoanhThu().ToString();
}
private void btnKetThuc_Click(object sender, EventArgs e)
{
this.Close();

120

}
}
}

121

Execution Result

122

Module 7
Exercise 1
Problem
Vit ch ng trnh c giao din v thc hin cc yu cu sau: Khi form c load
ln th ch c nt nhp liu , nt kt thc l s dng c, nt nhp d liu c
focus.
Khi nt nhp d liu c n th cc nt lnh khc c sng ln xo ni dung ca
Textbox nhp liu v Setfocus cho Textbox ny ( s dng ph ng thc Setfocus).
Khi mt trong cc nt ( ngoi tr nt Nhp D Liu v nt Kt Thc) c chn th
kt qu s hin th ln Textbox v cc nt lnh s b m (ngay c nt va nhn).

123

Code Listing
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace Bai01
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string[] arr = new string[100];
private string str;
private void btnNhapDuLieu_Click(object sender, EventArgs e)
{
str = txt1.Text;
btnDemSoKTHoa.Enabled = true;
btnInChuHoa.Enabled = true;
btnInSoTuTrenMoiDong.Enabled = true;
btnInChuThuong.Enabled = true;
btnDemSoTu.Enabled = true;
btnDemSoKTThuong.Enabled = true;
btnInNguyenAmPhuAm.Enabled = true;
arr = str.Split(' ');
}
private void Form1_Load(object sender, EventArgs e)
{
btnNhapDuLieu.Focus();
}
private void btnDemSoKTHoa_Click(object sender, EventArgs e)
{
int soKiTuHoa = 0;
foreach (char ch in str)
{
if (Char.IsUpper(ch)) soKiTuHoa++;
}
txt2.Text = "s k t hoa = " + soKiTuHoa.ToString();
}
private void btnInChuHoa_Click(object sender, EventArgs e)
{
txt2.Text = txt1.Text.ToUpper();
}
private void btnInSoTuTrenMoiDong_Click(object sender, EventArgs e)
{
txt2.Clear();

124

foreach (char c in txt1.Text)


{
if (c.ToString() == " ")
txt2.Text += "\n";
else txt2.Text += c.ToString();
}
}
private void btnInChuThuong_Click(object sender, EventArgs e)
{
txt2.Text = txt1.Text.ToLower();
}
private void btnDemSoTu_Click(object sender, EventArgs e)
{
txt2.Text = "c " + arr.Length + " t";
}
private void btnDemSoKTThuong_Click(object sender, EventArgs e)
{
int soKiTuThuong = 0;
foreach (char ch in txt1.Text)
{
if (char.IsLower(ch))
{
soKiTuThuong++;
}
}

txt2.Text = "s k t thng = " + soKiTuThuong.ToString();


}
private string[] CacPhuAm = {"b","c", "d", "", "g", "h", "k", "l", "m", "n",
"p", "q", "r", "s", "t", "v", "x"};
private void btnInNguyenAmPhuAm_Click(object sender, EventArgs e)
{
txt2.Clear();
HashSet<char> nguyenAm = new HashSet<char>();
HashSet<char> phuAm = new HashSet<char>();
foreach (char ch in txt1.Text)
{
bool flagPhuAm = false;
foreach(string s in CacPhuAm)
{
if(ch.ToString().ToLower() == s)
{
flagPhuAm = true;
}
}
if (flagPhuAm) phuAm.Add(ch);
else nguyenAm.Add(ch);
}
txt2.Text = "cc nguyn m : ";
foreach (char na in nguyenAm)
{

125

txt2.Text +=
}
txt2.Text += "\n
foreach (char pa
{
txt2.Text +=
}

na.ToString() + " ";


cc ph m : ";
in phuAm)
pa.ToString() + " ";

}
private void btnKetThuc_Click(object sender, EventArgs e)
{
this.Close();
}
}
}

Execution Result

126

127

128

129

Exercise 2
Problem
To mn hnh m s t nh sau

Da vo chui nhp , m s t nhp theo quy nh cc t ng n cch nhau bng


k t trng (space).

Code Listing

Execution Result

Exercise 3
Problem
To mt Project nh yu cu sau: Khi chn nt Search th ch ng trnh s thng
bo cho ngi s dng bit ni dung
nhp trong Search string c xut hin trong Main string hay khng Khi chn nt
Replace th ch ng trnh s thay th trong Main String chui gi tr Search String
bng chui Replace String.

Code Listing
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace Bai03
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnReplace_Click(object sender, EventArgs e)

130

{
rtxContent.SelectAll();
rtxContent.SelectionBackColor = Color.White;
rtxContent.Text = rtxContent.Text.Replace(txtSearch.Text,
txtReplace.Text);
}
private void btnSearch_Click(object sender, EventArgs e)
{
rtxContent.SelectAll();
rtxContent.SelectionBackColor = Color.White;
int i = 0;
foreach (char ch in rtxContent.Text)
{
if(ch.ToString().ToLower() == txtSearch.Text.ToLower())
{
rtxContent.Select(i, 1);
rtxContent.SelectionBackColor = Color.Yellow;
}
i++;
}
}
}
}

Execution Result

131

Exercise 4
Problem
Vit ch ng trnh thc hin vic thc hnh nh my ch, giao din nh hnh bn.
Yu cu : Khi nhn 1 k t hoc 1 s no th k t hoc s chuyn sang mu ,
khi th phm ra th mu ch tr li mu en. ng thi k t va c nhn s hin
bn di Text box.

Code Listing
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace Bai04
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string input = "";
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
//MessageBox.Show("code:" + e.KeyCode.ToString() + "\ndata:" +
e.KeyData.ToString() + "\nvalue:" +
//
e.KeyValue.ToString());

132

input = e.KeyData.ToString();
SuKienKeyDown();
}
private void richTextBox1_KeyUp(object sender, KeyEventArgs e)
{
input = e.KeyData.ToString();
SuKienKeyUp();
}
private void SuKienKeyDown()
{
foreach (Control ctrlChild in this.Controls)
{
if (ctrlChild.GetType() == typeof(Label))
{
if (ctrlChild.Text.ToUpper() == input.ToUpper())
{
ctrlChild.BackColor = Color.OrangeRed;
}
}
}
}

private void SuKienKeyUp()


{
foreach (Control ctrlChild in this.Controls)
{
if (ctrlChild.GetType() == typeof(Label))
{
if (ctrlChild.Text.ToUpper() == input.ToUpper())
{
ctrlChild.BackColor = Color.White;
}
}
}
}

}
}

133

Execution Result

Exercise 5
Problem
Thit k giao din v vit code thc hin nhng yu cu sau:
Cho php nhp mt chui H Tn
Xut H, Ch lt, Tn ca chui h tn vo cc label t ng ng khi click chut
vo mt nt lnh
To iu kin ngi s dng thun li khi nhp h tn mi.
C nt lnh ng ch ng trnh v phi hi ngi s dng trc khi tht s
kt thc ch ng trnh

Code Listing
using
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;

namespace Bai05

134

{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnThoat_Click(object sender, EventArgs e)
{
if(MessageBox.Show("Thot chng trnh ?","thng
bo",MessageBoxButtons.OKCancel,MessageBoxIcon.Question)==DialogResult.OK)
{
this.Close();
}
}
private void btnXuat_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(txtHoTen.Text))
{
MessageBox.Show("cha nhp h tn");
txtHoTen.Focus();
}
else
{
string input = txtHoTen.Text.Trim();
string[] arr = input.Split(' ');
if (arr.Length >= 2)
{
string ho = arr[0];
string ten = arr[arr.Length - 1];
lblHo.Text = ho;
lblTen.Text = ten;
string chuLot = "";
if (arr.Length > 2)
{
for (int i = 1; i < arr.Length - 1; i++)
{
chuLot += arr[i] + " ";
}
}
lblChuLot.Text = chuLot;
}
else
{
if (arr.Length <= 1)
{
MessageBox.Show("h tn cha y ");
txtHoTen.Focus();
}
}
}
}
}

135

Execution Result

136

También podría gustarte