TRƯỜNG ĐẠI HỌC CÔNG NGHIỆP THÀNH PHỐ HỒ CHÍ MINH
KHOA CÔNG NGHỆ NGHỆ THÔNG TIN
MÔN CÔNG NGHỆ DOTNET
BÀI TẬP THỰ C HÀNH
GIẢNG VIÊN: PHẠM QUẢNG TRI TRỊNH NGỌC HƯNG 07712961 HUỲNH HỒNG PHÚC 07711661
TP.Hồ Chí Minh tháng 3 năm 2012
Chương 2 Bài 1: Tạo giao diện như hình: nhậ p vào 2 s ố và 4 Radio, click vào Radio Cộng sẽ thự c hiện phép Cộng 2 số và xuấ t k ế ế t quả vào Label K ế ết quả. Thự c hiện tương tự cho các Radio còn l ại. (kiể m tra dữ liệu nhập phải là số ) Code: 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 S2Basic_Controls { public partial class Bai1_frmPhepTinh : Form { public Bai1_frmPhepTinh() { InitializeComponent(); } private void rdbCong_CheckedChanged( rdbCong_CheckedChanged(object object sender, EventArgs e) { float a, b, kq; if (rdbCong.Checked (rdbCong.Checked == true true) ) { try { a = float float.Parse(txtSoA.Text); .Parse(txtSoA.Text); b = float float.Parse(txtSoB.Text); .Parse(txtSoB.Text); kq = a + b; txtKetQua.Text txtKetQua.Text = kq.ToString(); kq.ToString(); } catch { txtKetQua.Text txtKetQua.Text = "gia tri khong hop le"; le" ; txtSoA.Focus(); } } else txtKetQua.Text txtKetQua.Text = "" ""; ; } private void Bai1_PhepTinh_Load( Bai1_PhepTinh_Load(object object sender, EventArgs e) { txtSoA.Text = "" ""; ; txtSoB.Text = "" ""; ; txtKetQua.Text txtKetQua.Text = "" ""; ; rdbCong.Checked rdbCong.Checked = rdbTru.Checked rdbTru.Checked = rdbNhan.Checked rdbNhan.Checked = rdbChia.Checked rdbChia.Checked = false; false ; }
private void rdbCong_Leave( object sender, EventArgs e) { //rdbCong.Checked //rdbCong.Ch ecked = false; } private void rdbTru_CheckedChanged( rdbTru_CheckedChanged(object object sender, EventArgs e) { float a, b, kq; if (rdbTru.Checked (rdbTru.Checked == true true) ) { try { a = float float.Parse(txtSoA.Text); .Parse(txtSoA.Text); b = float float.Parse(txtSoB.Text); .Parse(txtSoB.Text); kq = a - b; txtKetQua.Text txtKetQua.Text = kq.ToString(); kq.ToString(); } catch { txtKetQua.Text txtKetQua.Text = "gia tri khong hop le"; le" ; txtSoA.Focus(); } } else txtKetQua.Text txtKetQua.Text = "" ""; ; } private void rdbNhan_CheckedChanged( rdbNhan_CheckedChanged(object object sender, EventArgs e) { float a, b, kq; if (rdbNhan.Checked (rdbNhan.Checked == true true) ) { try { a = float float.Parse(txtSoA.Text); .Parse(txtSoA.Text); b = float float.Parse(txtSoB.Text); .Parse(txtSoB.Text); kq = a * b; txtKetQua.Text txtKetQua.Text = kq.ToString(); kq.ToString(); } catch { txtKetQua.Text txtKetQua.Text = "gia tri khong hop le"; le" ; txtSoA.Focus(); } } else txtKetQua.Text txtKetQua.Text = "" ""; ; } private void rdbChia_CheckedChanged( rdbChia_CheckedChanged(object object sender, EventArgs e) { float a, b, kq; if (rdbChia.Checked (rdbChia.Checked == true true) ) { try { a = float float.Parse(txtSoA.Text); .Parse(txtSoA.Text); b = float float.Parse(txtSoB.Text); .Parse(txtSoB.Text); kq = a / b; txtKetQua.Text txtKetQua.Text = kq.ToString(); kq.ToString(); }
catch (DivideByZeroException DivideByZeroException) ) { txtKetQua.Text txtKetQua.Text = "Loi chia cho 0"; 0" ; //MessageBox.Show("Loi //MessageBox .Show("Loi " + e.ToString() e.ToString()); ); txtSoB.Focus(); } catch { txtKetQua.Text txtKetQua.Text = "gia tri khong hop le"; le" ; txtSoA.Focus(); } } else txtKetQua.Text txtKetQua.Text = "" ""; ; } } }
Execution Result:
Bài 2: Viết chương trình dùng để định dạng LABEl TEXT theo các Checkbox và Radio button tương ứ ng ng (Font Style, Color). Code: 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 S2Basic_Controls { public partial class Bai2_frmDinhDangChu : Form { public Bai2_frmDinhDangChu() {
InitializeComponent(); } private void chbRegular_CheckedChanged( chbRegular_CheckedChanged(object object sender, EventArgs e) { //CheckBox chb = sender as CheckBox; if(chbRegular. if (chbRegular.Checked Checked == true true) ) lbText.Font = new Font Font(lbText.Font, (lbText.Font, lbText.Font.Style lbText.Font.Style ^ FontStyle.Regular); FontStyle .Regular); } private void chbBold_CheckedChanged( chbBold_CheckedChanged(object object sender, EventArgs e) { FontStyle re = lbText.Font.Style; lbText.Font.Style; if (chbBold.Checked (chbBold.Checked == true true) ) lbText.Font = new Font Font(lbText.Font, (lbText.Font, lbText.Font.Style lbText.Font.Style ^ FontStyle.Bold); FontStyle .Bold); else lbText.Font = new Font Font(lbText.Font, (lbText.Font, FontStyle FontStyle.Regular); .Regular); } private void chbItalic_CheckedChanged( chbItalic_CheckedChanged(object object sender, EventArgs e) { if (chbItalic.Checked (chbItalic.Checked == true true) ) lbText.Font = new Font Font(lbText.Font, (lbText.Font, lbText.Font.Style^FontStyle lbText.Font.Style^FontStyle.Italic); .Italic); else lbText.Font = new Font Font(lbText.Font, (lbText.Font, FontStyle FontStyle.Regular); .Regular); } private void chbBandI_CheckedChanged( chbBandI_CheckedChanged(object object sender, EventArgs e) { if (chbBandI.Checked (chbBandI.Checked == true true) ) lbText.Font = new Font Font(lbText.Font, (lbText.Font, lbText.Font.Style^ lbText.Font.Style^FontStyle FontStyle.Bold .Bold | lbText.Font.Style^FontStyle lbText.Font.Style^FontStyle.Italic); .Italic); else lbText.Font = new Font Font(lbText.Font, (lbText.Font, FontStyle FontStyle.Regular); .Regular); } private void rdbRed_CheckedChanged( rdbRed_CheckedChanged(object object sender, EventArgs e) { if (rdbRed.Checked (rdbRed.Checked == true true) ) lbText.ForeColor lbText.ForeColor = Color Color.Red; .Red; } private void rdbGreen_CheckedChanged( rdbGreen_CheckedChanged(object object sender, EventArgs e) { if (rdbGreen.Checked (rdbGreen.Checked == true true) ) lbText.ForeColor lbText.ForeColor = Color Color.Green; .Green; } private void rdbBlue_CheckedChanged( rdbBlue_CheckedChanged(object object sender, EventArgs e) { if (rdbBlue.Checked (rdbBlue.Checked == true true) ) lbText.ForeColor lbText.ForeColor = Color Color.Blue; .Blue; } private void rdbAuto_CheckedChanged( rdbAuto_CheckedChanged(object object sender, EventArgs e) { Random rand = new Random Random(); (); int red = rand.Next(100); rand.Next(100);
int gre = rand.Next(200); rand.Next(200); int blu = rand.Next(300); rand.Next(300); lbText.ForeColor lbText.ForeColor = Color Color.FromArgb(red .FromArgb(red, , gre, blu); } private void Bai2_frmDinhDangChu_Load( Bai2_frmDinhDangChu_Load(object object sender, EventArgs e) { } } }
Execution Result:
Bài 3: Viết chương trình dùng để định dạng TEXTBOX theo các font ch ữ tương ứ ng ng với từ ng ng Radio button. Code: 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 S2Basic_Controls { public partial class Bai3_frmDinhDangFontChu : Form { public Bai3_frmDinhDangFontChu() {
InitializeComponent(); } private void rdbTimesNewRoman_CheckedChanged( rdbTimesNewRoman_CheckedChanged(object object sender, EventArgs e) { //txtMau.Font //txtMau.Fon t = new Font(rdbTimesNewRoman.Font.Name, Font(rdbTimesNewRoman.Font.Name, 30f); //string s = rdbTimesNewRoman.Font.Name; txtMau.Font = new Font Font( ("Times New Roman", Roman" , 30f); //MessageBox.Show(s); } private void rdbArial_CheckedChanged( rdbArial_CheckedChanged(object object sender, EventArgs e) { txtMau.Font = new Font Font(rdbArial.Fon (rdbArial.Font.Name, t.Name, 30f); } private void rdbTahoma_CheckedChanged( rdbTahoma_CheckedChanged(object object sender, EventArgs e) { txtMau.Font = new Font Font(rdbTahoma.Fo (rdbTahoma.Font.Name, nt.Name, 30f); } private void rdbCourierNew_CheckedChanged( rdbCourierNew_CheckedChanged(object object sender, EventArgs e) { txtMau.Font = new Font Font(rdbCourierNe (rdbCourierNew.Font.Name, w.Font.Name, 30f); } } }
Execution Result:
Bài 4: Viết chương trình Quả n lý thu ti ền ền cho quán Café Sinh Viên như sau:
Khi nhóm khách hàng vào quán g ọi café sẽ được chọn 1 trong các loại café. Giá cho t ừ ng ng loại café tương ứng như sau:
Café đen: 20.000đ
Café đá: 25.000đ Café sữ a: a: 25.000đ Café sữa đá: 30.000đ Café kem: 35.000đ Khi khách hàng g ọi tính ti ề ền, thu ngân s ẽ nhập thông tin tên khách hàng và tùy vào lo ại café thì sẽ có giá tương ứng ( lưu ý: nế u khách hàng là Sinh Viên – check vào checkbox Sinh Viên – thì sẽ được giảm giá 20%). Cu ố i cùng thu ngân sẽ tính tổng số người trong nhóm và thanh toán ti ề ền.
Chương trình thự c hiện: - Form_Load: con trỏ văn bản đặt vào ô tên khách hàng, các button TinhTien, NhapLai, ThanhToan b ị mờ (enabled=false). Thự c hi ện nh ập tên khách hàng (tên khách hàng không được để trố ng). ng). Check vào checkbox Sinh Viên n ế u khách hàng là Sinh Viên, chọn loại café mà khách hàng đã gọ i. Khi nhập đầy đủ thông tin thì btnTinhTien có tác d ụng. - btnTinhTien _Click: thự c hiện tính ti ề ền cho khách hàng v ừ a nhập và hiể n thị lên messagebox, đồng thời lưu lại thông tin tổng số ti ề ền và tổng số lượ ố lượt khách. btnNhapLai, btnThanhToan sáng lên sẵn sàng cho vi ệc nhập khách hàng m ới hoặc thanh toán ti ề ền. - btnNhapLai_Click: khởi tạo lại trạng thái ban đầ u của Form, btnNhapLai bị mờ. - btnThanhToan_Click: Ghi l ại thông tin tổng số khách và t ổng ti ề ền Thanh toán vào các label tương ứ ng ng, đồng thời khởi tạo lại giá trị tổng số khách hàng =0, t ổng ti ề ền thanh toán =0, s ẵn sàng cho việc nhập nhóm khách hàng m ới. btnThanhToan b ị mờ. - btnThoat_Click: hỏi người dùng có chắc chắn thoát khỏi chương trình hay không? Yes: thoát, No: không. Code: 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 S2Basic_Controls {
public partial class Bai4_frmCoffee : Form { private float tongTien = 0; private int tongNguoi = 0; private float isSV = 0.2f; private readonly int cafeDen = 20000; private readonly int cafeDa = 25000; private readonly int cafeSua = 30000; private readonly int cafeSuaDa = 35000; private readonly int cafeKem = 35000; public Bai4_frmCoffee() { InitializeComponent(); } private void txtHoTen_Leave(object txtHoTen_Leave(object sender, EventArgs e) { //if(btnThoat.Click==null) if (txtHoTen.Text (txtHoTen.Text == "" "") ) { MessageBox.Show( MessageBox .Show("Ho "Ho ten khong the rong"); rong" ); txtHoTen.Focus(); } } private void Bai4_frmCoffee_Load( Bai4_frmCoffee_Load(object object sender, EventArgs e) { btnTinhTien.Enabled btnTinhTien.Enabled = false false; ; btnNhapLai.Enabled btnNhapLai.Enabled = false false; ; btnThanhToan.Enabled btnThanhToan.Enabled = false false; ; } private void rdbDen_CheckedChanged( rdbDen_CheckedChanged(object object sender, EventArgs e) { RadioButton rdb = sender as RadioButton RadioButton; ; if (rdb.Checked == true true) ) { btnTinhTien.Enabled btnTinhTien.Enabled = true true; ; } } private void btnTinhTien_Click( object sender, EventArgs e) { tongNguoi++; if (rdbDa.Checked (rdbDa.Checked == true true) ) tongTien += cafeDa; else if (rdbDen.Checked (rdbDen.Checked == true true) ) tongTien += cafeDen; else if (rdbSua.Checked (rdbSua.Checked == true true) ) tongTien += cafeSua; else if (rdbSuaDa.Checked (rdbSuaDa.Checked == true true) ) tongTien += cafeSuaDa; else tongTien += cafeKem; if (chbIsSinhVien.Checked (chbIsSinhVien.Checked == true true) ) tongTien = tongTien - tongTien * isSV; //cho phep nhap tiep hoac thanh toan btnNhapLai.Enabled btnNhapLai.Enabled = true true; ; btnThanhToan.Enabled btnThanhToan.Enabled = true true; ; }
private void btnNhapLai_Click(object btnNhapLai_Click(object sender, EventArgs e) { txtHoTen.Text txtHoTen.Text = "" ""; ; chbIsSinhVien.Checked chbIsSinhVien.Checked = false false; ; Bai4_frmCoffee_Load(null Bai4_frmCoffee_Load( null, , null null); ); txtHoTen.Focus(); } private void btnThanhToan_Click( btnThanhToan_Click(object object sender, EventArgs e) { txtSoNguoi.Text txtSoNguoi.Text = tongNguoi.ToString(); tongNguoi.ToString(); txtTongTien.Text txtTongTien.Text = tongTien.ToString(); tongTien.ToString(); tongTien = tongNguoi = 0; btnNhapLai_Click(null btnNhapLai_Click(null, ,null null); ); } private void btnThoat_Click(object btnThoat_Click(object sender, EventArgs e) { DialogResult r = MessageBox MessageBox.Show( .Show("ban "ban co muon thoat", thoat" , "o thoat", thoat", MessageBoxButtons.YesNo); MessageBoxButtons .YesNo); if (r == DialogResult .Yes) this.Close(); this .Close(); } private void txtHoTen_TextChanged( txtHoTen_TextChanged(object object sender, EventArgs e) { } } }
Execution Result:
Bài 5: Viết chương trình kiể m tra sứ c khỏe của 1 ngườ i bằng cách nhập vào ều cao (cm), cân n ặng (kg) d ữ các thông số : họ tên (không được rỗng), chi ề liệu vày phải là số . Tính cân s ố cân chuẩ n của người đó theo công thứ c sau (tùy theo Nam hay N ữ ): ): Công thứ c tính cân nặng chuẩn: Cân nặng lý tưởng (kg) = T – 100 – (T –150/ N) (Trong đó: T là chiều cao (cm), N = 4 v ới Nam và N = 2 v ới Nữ .) .) - btnTinh: Thự c hiện tính số cân chuẩ n theo công thức, sau đó hiể n thị k ế ế t quả vào label k ế ế t quả như hình. - btnXoa: trả lại trạng ban đầu của Form, cho phép nhập người mới - btnThoat: thoát khỏi chương trình. Code: 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 S2Basic_Controls { public partial class Bai5_frmKiemTraSucKhoe : Form { private int heso; public Bai5_frmKiemTraSucKhoe() { InitializeComponent(); } private void txtCanNang_TextChanged( txtCanNang_TextChanged(object object sender, EventArgs e) { } private void txtChiSo_KeyPress( object sender, KeyPressEventArgs e) { if (!Char (!Char.IsDigit(e. .IsDigit(e.KeyChar) KeyChar) && !Char Char.IsControl(e.KeyChar)) .IsControl(e.KeyChar)) e.Handled = true true; ; } private void txtHoTen_Leave(object txtHoTen_Leave(object sender, EventArgs e) { if (txtHoTen.Text (txtHoTen.Text == "" "") ) { MessageBox.Show( MessageBox .Show("Ho "Ho ten khong duoc de trong"); trong" ); txtHoTen.Focus(); } } private void btnTinh_Click( object sender, EventArgs e) { int cannang = int int.Parse(txtCanNang.Text); .Parse(txtCanNang.Text); //MessageBox.Show(cannan //MessageBo x.Show(cannang.ToString() g.ToString()); ); int chieucao = int int.Parse(txtChieuCao.Text); .Parse(txtChieuCao.Text); //MessageBox.Show(chieuc //MessageBo x.Show(chieucao.ToString( ao.ToString()); )); if (rdbNam.Checked (rdbNam.Checked == true true) ) heso = 4; else heso = 3; int trungbinh = (int ( int) )Math Math.Abs(chieuca .Abs(chieucao o - 100 - (chieucao - 150) / heso); lbNx1.Text = "Can Nang Li Tuong Cua Ban " + txtHoTen.Text + " la: " + trungbinh.ToString(); //MessageBox.Show(trungb //MessageBox .Show(trungbinh.ToString( inh.ToString()); )); if (cannang > trungbinh) lbNx2.Text = "ban dang thua can, hay giam :D" ; else if (cannang < trungbinh) lbNx2.Text = "Ban dang thieu can, hay tang :D" ; else lbNx2.Text = "ban vua can, dat. :D"; :D" ; } private void Bai5_frmKiemTraSucKhoe_Load( Bai5_frmKiemTraSucKhoe_Load(object object sender, EventArgs e) { rdbNu.Checked rdbNu.Checked = true true; ; } private void btnXoa_Click(object btnXoa_Click(object sender, EventArgs e) {
txtHoTen.Text txtHoTen.Text = "" ""; ; txtCanNang.Text txtCanNang.Text = "" ""; ; txtChieuCao.Text txtChieuCao.Text = "" ""; ; lbNx2.Text = "" ""; ; lbNx1.Text = "" ""; ; txtHoTen.Focus(); } private void btnThoat_Click(object btnThoat_Click(object sender, EventArgs e) { DialogResult r = MessageBox MessageBox.Show( .Show("Ban "Ban co muon thoat", thoat" , "Hop thoat", thoat" , MessageBoxButtons.YesNo); MessageBoxButtons .YesNo); if (r == DialogResult .Yes) this.Close(); this .Close(); } } }
Execution Result:
ền phòng cho Khách sạn Thanh Bài 6: Viết chương trình Quả n lýThanh toán ti ề Thanh như sau: Khi khách tr ả phòng, nhân viên k ế ế toán sẽ thự c hiện kiể m tra tên, địa chỉ, số ngày ở, loại phòng, tiện nghi và dịch vụ của khách. Sau đây là bả ng giá: o Loại phòng:
Phòng đơn: Phòng đôi:
300.000đ/1 ngày 350.000đ/1 ngày
o o
Phòng ba: 400.000đ/1 ngày Tiện nghi: mỗi loại cộng thêm 10.000đ Dịch vụ: Karaoke: 50.000đ
Ăn sáng:
15.000đ/1 ngày
Cuố i ngày Nhân viên k ế ế toán sẽ thố ng ng kê tổng s ố lượt ố lượt người tr ả phòng, tổng số ti ền ền thu được trong ngày.
Chương trình thự c hiện: - Form_Load: con trỏ văn bản đặt vào ô tên khách hàng, các button TongKet, NhapMoi, ThanhToan b ị mờ (enabled=false). Thự c hiện nhập tên (tên khách không được để trống), địa chỉ, số ngày ở (number), check vào lo ại phòng, tiện nghi, d ịch vụ mà khách đã thuê. Khi nhập đầy đủ thông tin thì btnThanhToan có tác dụng. - btnThanhToan: th ự c hiện tính ti ề ền cho khách v ừ a nhập và hiể n thị lên label Thành Ti ền, ền, đồ ng thời lưu lại thông tin tổng s ố ti ề ền và tổng số lượt khách. btnNhapMoi, btnTongKet sáng lên s ẵn sàng cho việc nhập khách mới. - btnNhapMoi: khởi tạo lại trạng thái ban đầ u của Form, btnNhapMoi bị mờ. - btnTôngKet: Ghi lại thông tin tổng số khách và t ổng ti ề ền Thanh toán vào các label tương ứng, đồ ng thời khởi tạo l ại giá trị tổng số khách hàng =0, t ổng ti ề ền thanh toán =0. btnTongKet b ị mờ. - btnThoat_Click: hỏi người dùng có chắc chắn thoát khỏi chương trình hay không? Yes: thoát, No: không. Code: 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 S2Basic_Controls { public partial class Bai6_frmKhachSanThanhThanh : Form { //fields can thiet trong app private int tongNguoi = 0; private long tongTien = 0;
private int[] int[] giaPhong = { 300000, 350000, 400000 }; private int giaTienNghi = 10000; private int int[] [] giaDV = { 50000, 150000 }; public enum LoaiPhong { phongDon, phongDoi, phongBa } public enum DichVu { karaoke, ansang } public Bai6_frmKhachSanThanhThanh() { InitializeComponent(); } private void txtHoTen_Leave(object txtHoTen_Leave(object sender, EventArgs e) { if (txtHoTen.Text (txtHoTen.Text == "" "") ) { MessageBox.Show( MessageBox .Show("ten "ten khong duoc rong"); rong" ); txtHoTen.Focus(); } } private void Bai6_frmKhachSanThanhThanh_Load( Bai6_frmKhachSanThanhThanh_Load(object object sender, EventArgs e) { txtHoTen.Focus(); //txtDiaChi.Text = ""; //txtDiaChi.Select(); btnNhapMoi.Enabled btnNhapMoi.Enabled = false false; ; btnThanhToan.Enabled btnThanhToan.Enabled = false false; ; btnTongKet.Enabled btnTongKet.Enabled = false false; ; rdbPhongDon.Checked rdbPhongDon.Checked = true true; ; //chbTiVi.Checked //chbTiVi.Ch ecked = true; //chbKaraoke.Checked = true; } private void txtSoNgayO_KeyPress( txtSoNgayO_KeyPress(object object sender, KeyPressEventArgs e) { if (!char (!char.IsDigit(e. .IsDigit(e.KeyChar) KeyChar) && !char char.IsControl(e.KeyChar)) .IsControl(e.KeyChar)) e.Handled = true true; ; } private void txtSoNgayO_Leave(object txtSoNgayO_Leave(object sender, EventArgs e) { btnThanhToan.Enabled btnThanhToan.Enabled = true true; ; //btnTongKet.Enabled = true; } private void btnThanhToan_Click( btnThanhToan_Click(object object sender, EventArgs e) { //string s = ((int)LoaiPhong.phongBa).ToString(); //MessageBox.Show(s); int songayo = int int.Parse(txtSoNgayO.Text); .Parse(txtSoNgayO.Text); long thanhtien;
int gphong, gtn = 0, gdv = 0; //lay gia phong if (rdbPhongDon.Checked (rdbPhongDon.Checked == true true) ) gphong = giaPhong[(int giaPhong[( int) )LoaiPhong LoaiPhong.phongDon]; .phongDon]; else if (rdbPhongDoi.Checked (rdbPhongDoi.Checked == true true) ) gphong = giaPhong[(int giaPhong[( int) )LoaiPhong LoaiPhong.phongDoi]; .phongDoi]; else gphong = giaPhong[(int giaPhong[( int) )LoaiPhong LoaiPhong.phongBa]; .phongBa]; //tien tien nghi if (chbTiVi.Checked (chbTiVi.Checked == true||chbInternet.Checked== true ||chbInternet.Checked==true true||chbMayNcNong.Checked== ||chbMayNcNong.Checked==true true) ) gtn += giaTienNghi; giaTienNghi; //lay tien dich vu if(chbKaraoke.Checked== if (chbKaraoke.Checked==true true) ) gdv+=giaDV[(int gdv+=giaDV[(int) )DichVu DichVu.karaoke]; .karaoke]; if(chbAnSang.Checked== if (chbAnSang.Checked==true true) ) gdv+=giaDV[(int gdv+=giaDV[(int) )DichVu DichVu.ansang]; .ansang]; thanhtien = (gphong + gtn + gdv) * songayo; //xuat thanh tien ra txtThanhTien.Text txtThanhTien.Text = thanhtien.ToString() thanhtien.ToString() + " vnd"; vnd"; //hien nhap moi btnNhapMoi.Enabled btnNhapMoi.Enabled = true true; ; btnTongKet.Enabled btnTongKet.Enabled = true; true; //cap nhat so nguoi o va tong tien tongNguoi++; tongTien += thanhtien; } private void btnNhapMoi_Click(object btnNhapMoi_Click(object sender, EventArgs e) { txtHoTen.Text txtHoTen.Text = "" ""; ; txtDiaChi.Text txtDiaChi.Text = "" ""; ; txtSoNgayO.Text txtSoNgayO.Text = "" ""; ; txtThanhTien.Text txtThanhTien.Text = "" ""; ; lbSoLuotNguoi.Text lbSoLuotNguoi.Text = "" ""; ; lbTongSoTien.Text lbTongSoTien.Text = "" ""; ; Bai6_frmKhachSanThanhThanh_Load(null Bai6_frmKhachSanThanhThanh_Load( null, , null null); ); } private void btnTongKet_Click(object btnTongKet_Click(object sender, EventArgs e) { lbTongSoTien.Text lbTongSoTien.Text = tongTien.ToString() tongTien.ToString() + " vnd"; vnd"; lbSoLuotNguoi.Text = tongNguoi.ToString() + " vnd"; vnd"; //reset lai tong tien va tong nguoi tongNguoi = 0; tongTien = 0; //button tong ket bi mo btnThanhToan.Enabled btnThanhToan.Enabled = false false; ; btnTongKet.Enabled btnTongKet.Enabled = false false; ; } private void btnThoat_Click(object btnThoat_Click(object sender, EventArgs e) { this.Close(); this .Close(); }
} }
Execution Result:
Chương 3:
Bài 1: Vi Viết chương trình thự c hiện như sau ( xem hình bên dướ i) - Form_load: nhập số vào Textbox (nhớ kiể m tra dữ liệu nhập) - btnCapNhat: thêm số vừ a nhập vào Combobox, đồng thời xóa textbox nhập, đặt con trỏ lại textbox nhập. - Khi người dùng chọn 1 s ố trong ố trong Combobox thì danh sách các ước số của số này sẽ hiể n thị vào Listbox bên phải tương ứ ng. ng. - Khi nhấn Các button Tính: “Tổng các ướ c số”, “Số lượng “Số lượng các ước s ố chẵn”, “Số lượng các ước số nguyên tố” thì sẽ hiể n thị thông tin
tương ứ ng ng vào messagebox d ựa vào các ướ c số trên listbox. btnThoat: thoát khỏi ứ ng ng dụng. Code: using using using using using using
System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq;
using System.Text; using System.Windows.Forms; namespace SW3Basic_Controls2 { public partial class Bai1_frmCombobox : Form { public Bai1_frmCombobox() { InitializeComponent(); } private void txtNhap_KeyPress(object txtNhap_KeyPress(object sender, KeyPressEventArgs e) { if (!char (!char.IsControl( .IsControl(e.KeyChar) e.KeyChar) && ! Char Char.IsDigit(e.KeyChar)) .IsDigit(e.KeyChar)) e.Handled = true true; ; } private void btnNhap_Click( object sender, EventArgs e) { if(txtNhap.Text!= if (txtNhap.Text!="" "") ) cbbNhap.Items.Add(txtNhap.Text); txtNhap.Text = "" ""; ; txtNhap.Focus(); } private void Bai1_frmCombobox_Load( Bai1_frmCombobox_Load(object object sender, EventArgs e) { txtNhap.Text = "" ""; ; txtNhap.Focus(); } private void cbbNhap_SelectedIndexChanged( cbbNhap_SelectedIndexChanged(object object sender, EventArgs e) { int so = int int.Parse(( .Parse((string string)cbbNhap.SelectedItem); )cbbNhap.SelectedItem); string[] string [] items = TimUocSo(so); //foreach(string //foreach(st ring s in items) // MessageBox.Show(s); lsbUocSo.Items.Clear(); lsbUocSo.Items.AddRange(items); } private string string[] [] TimUocSo(int TimUocSo(int value) { //dung tim uoc so cho gia tri truyen vao. int item = 1, i = 0; string[] string [] items=new items=new string string[100]; [100]; while (item < value) { if (value % item == 0) { items[i] = item.ToString(); item.ToString(); i++; } item++; } items[i] = value.ToString(); string[] string [] us = new string string[i+1]; [i+1]; for (int j = 0; j <= i;j++ ) {
us[j] = items[j]; } return us; } private void btnTongUocSo_Click( btnTongUocSo_Click(object object sender, EventArgs e) { long tong = 0; for (int i = 0; i < lsbUocSo.Items.Count; lsbUocSo.Items.Count; i++) { lsbUocSo.SetSelected(i, true true); ); tong += int int.Parse(( .Parse((string string)lsbUocSo.SelectedItem); )lsbUocSo.SelectedItem); } //for (int i = 0; i < obj.Length - 1; i++) // tong += int.Parse(obj int.Parse(obj[i].ToString [i].ToString()); ()); MessageBox.Show( MessageBox .Show("TOng "TOng uoc so la: " + tong.ToString()); tong.ToString()); } private void btnSoLuongUSChan_Click( btnSoLuongUSChan_Click(object object sender, EventArgs e) { int count = 0; for (int i = 0; i < lsbUocSo.Items.Count; lsbUocSo.Items.Count; i++) { lsbUocSo.SetSelected(i, true true); ); if (int int.Parse(( .Parse((string string)lsbUocSo.Se )lsbUocSo.SelectedItem) lectedItem) % 2 == 0) count++; } MessageBox.Show( MessageBox .Show("So "So uoc so chan la: " + count.ToString()); count.ToString()); } private void btnSoLuongSoNTo_Click( btnSoLuongSoNTo_Click(object object sender, EventArgs e) { int count = 0; for (int i = 0; i < lsbUocSo.Items.Count; lsbUocSo.Items.Count; i++) { lsbUocSo.SetSelected(i, true true); ); if (LaSoNTo(int (LaSoNTo(int.Parse(( .Parse((string string)lsbUocSo.SelectedItem))) )lsbUocSo.SelectedItem))) { count++; MessageBox.Show(( MessageBox .Show((string string)lsbUocSo.SelectedItem); )lsbUocSo.SelectedItem); } } MessageBox.Show( MessageBox .Show("So "So uoc so la so nguyen to la: " + count.ToString()); count.ToString()); } private bool LaSoNTo(int LaSoNTo( int value) { int term = 2; while(term
} } }
Execution Result:
Bài 2: Viết chương trình thêm các phầ n tử vào listbox (listbox đượ c chọn nhi ề ều ph ần tử ) các số tự nhiên ự nhiên N được nhập từ textbox Viế t code cho các nút lệnh thự c hiện các công việc sau: - Tính tổng các phẩ n tử trong Listbox, hiể n thị lên Messagebox. - Xóa ph ần tử đầ ử đầu và cuố i của listbox.
ử đang chọn trong listbox. - Xóa các ph ần tử đang - Tăng giá trị mỗi ph ần tử lên 2. - Thay m ỗi giá trị của m ỗi ph ần t ử bằng bình pương của chính nó - Thự c hiện chọn các ph ần tử trong listbox là số chẵn. - Thự c hiện chọn các ph ần tử trong listbox là số lẻ. Code:
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 SW3Basic_Controls2 { public partial class Bai2_frmListBox : Form { public Bai2_frmListBox() { InitializeComponent(); } private void txtNhap_KeyPress(object txtNhap_KeyPress(object sender, KeyPressEventArgs e) { if (!char (!char.IsDigit(e. .IsDigit(e.KeyChar) KeyChar) && !char char.IsControl(e.KeyChar)) .IsControl(e.KeyChar)) e.Handled = true true; ; } private void btnNhap_Click( object sender, EventArgs e) { if (txtNhap.Text != "" "") ) lsbDuLieu.Items.Add(txtNh lsbDuLieu.Items.Add(txtNhap.Text); ap.Text); txtNhap.Text = "" ""; ; //txtNhap.Select(); txtNhap.Focus(); } private void Bai2_frmListBox_Load( Bai2_frmListBox_Load(object object sender, EventArgs e) { txtNhap.Focus(); } private void btnTongPhanTu_Click( btnTongPhanTu_Click(object object sender, EventArgs e) { //ICollection //ICollectio n ico = (ICollection< (ICollection)lsbDu object>)lsbDuLieu.Selecte Lieu.SelectedItems; dItems; //Array arr = ico as Array; //int tong = 0; //foreach (object o in arr) //{ // tong += int.Parse((s int.Parse((string)o); tring)o); //} //MessageBox.Show(tong.T //MessageBox .Show(tong.ToString()); oString()); int tong = 0; //clear cac item da duoc chon lsbDuLieu.SelectedItems.Clear(); for (int i = 0; i < lsbDuLieu.Items.Count; lsbDuLieu.Items.Count; i++) { lsbDuLieu.SetSelected(i, true true); ); tong += int int.Parse(( .Parse((string string)lsbDuLieu.SelectedItem); )lsbDuLieu.SelectedItem); } //clear cac item da select de tinh lsbDuLieu.SelectedItems.Clear(); //show tong gia tri MessageBox.Show( MessageBox .Show("tong "tong phan tu trong listbox la: " + tong.ToString()); tong.ToString());
} private void btnXoaDauVaCuoi_Click( btnXoaDauVaCuoi_Click(object object sender, EventArgs e) { //xoa phan tu cuoi if(lsbDuLieu.Items.Count>=1) if (lsbDuLieu.Items.Count>=1) lsbDuLieu.Items.RemoveAt( lsbDuLieu.Items.RemoveAt(lsbDuLieu.It lsbDuLieu.Items.Count ems.Count - 1); //xoa phan tu dau if(lsbDuLieu.Items.Count>=1) if (lsbDuLieu.Items.Count>=1) lsbDuLieu.Items.RemoveAt(0); } private void btnXoaDangChon_Click( btnXoaDangChon_Click(object object sender, EventArgs e) { //for (int i = 0; i < lsbDuLieu.Items.Count; lsbDuLieu.Items.Count; i++) //{ // if(lsbDuLieu.s) //} int se = lsbDuLieu.SelectedIndex; lsbDuLieu.SelectedIndex; //int [] see = new int(lsbDuLieu.SelectedIndices); int(lsbDuLieu.SelectedIndices); while (se != -1) { MessageBox.Show(se.ToString()); MessageBox .Show(se.ToString()); lsbDuLieu.Items.RemoveAt(se); se = lsbDuLieu.SelectedIndex; lsbDuLieu.SelectedIndex; } //MessageBox.Show(se.ToString()); } private void btnTangLen2_Click( object sender, EventArgs e) { lsbDuLieu.SelectedIndice lsbDuLieu.SelectedIndices.Clear(); s.Clear(); string[] string [] items = new string string[lsbDuLieu.Items.Count]; [lsbDuLieu.Items.Count]; for (int i = 0; i < lsbDuLieu.Items.Count; lsbDuLieu.Items.Count; i++) { lsbDuLieu.SetSelected(i, true true); ); items[i] = (int (int.Parse(( .Parse((string string)lsbDuLieu.S )lsbDuLieu.SelectedItem) electedItem) + 2).ToString(); 2).ToString(); lsbDuLieu.SetSelected(i, false false); ); } lsbDuLieu.Items.Clear(); lsbDuLieu.Items.AddRange(items); } private void btnBinhPhuong_Click( btnBinhPhuong_Click(object object sender, EventArgs e) { lsbDuLieu.SelectedIndice lsbDuLieu.SelectedIndices.Clear(); s.Clear(); string[] string [] items = new string string[lsbDuLieu.Items.Count]; [lsbDuLieu.Items.Count]; for (int i = 0; i < lsbDuLieu.Items.Count; lsbDuLieu.Items.Count; i++) { lsbDuLieu.SetSelected(i, true true); ); items[i] = Math.Pow(( Math .Pow((int int.Parse(( .Parse((string string)lsbDuLieu.SelectedItem)),2).ToString(); )lsbDuLieu.SelectedItem)),2).ToString(); lsbDuLieu.SetSelected(i, false false); ); } lsbDuLieu.Items.Clear(); lsbDuLieu.Items.AddRange(items); } private void btnChonSoChan_Click( btnChonSoChan_Click(object object sender, EventArgs e) {
lsbDuLieu.SelectedItems.Clear(); int[] int [] sel = new int int[lsbDuLieu.Items.Count]; [lsbDuLieu.Items.Count]; for (int i = 0; i < lsbDuLieu.Items.Count; lsbDuLieu.Items.Count; i++) { lsbDuLieu.SetSelected(i,true lsbDuLieu.SetSelected(i, true); ); if (int int.Parse(( .Parse((string string)lsbDuLieu.S )lsbDuLieu.SelectedItem) electedItem) % 2 == 0) sel[i] = 1; lsbDuLieu.SetSelected(i, false false); ); } for (int i = 0; i < lsbDuLieu.Items.Count; lsbDuLieu.Items.Count; i++) if (sel[i] == 1) lsbDuLieu.SetSelected(i, true true); ); } private void btnChonSoLe_Click( object sender, EventArgs e) { lsbDuLieu.SelectedItems.Clear(); int[] int [] sel = new int int[lsbDuLieu.Items.Count]; [lsbDuLieu.Items.Count]; for (int i = 0; i < lsbDuLieu.Items.Count; lsbDuLieu.Items.Count; i++) { lsbDuLieu.SetSelected(i, true true); ); if (int int.Parse(( .Parse((string string)lsbDuLieu.S )lsbDuLieu.SelectedItem) electedItem) % 2 != 0) sel[i] = 1; lsbDuLieu.SetSelected(i, false false); ); } for (int i = 0; i < lsbDuLieu.Items.Count; lsbDuLieu.Items.Count; i++) if (sel[i] == 1) lsbDuLieu.SetSelected(i, true true); ); } private void btnKetThuc_Click(object btnKetThuc_Click(object sender, EventArgs e) { this.Close(); this .Close(); } } }
Execution Result:
Bài 3: Viết chương trình nhậ p danh sách các Sinh Viên theo yêu c ầu sau:
(xem hình bên dướ i). Các listbox được phép chọn nhi ề ều mục (k ế ế t hợp giữ a phím Shift, Ctrl và chuột)
Khi người dùng nhập họ và tên của Sinh viên vào Textbox, click nút Cập Nhật thì tên Sinh Viên đó sẽ được nhập vào Listbox Trái. ,
chuyển các tên đang chọ n từ Lisxtbox Trái sang Listbox
Phải và ngược lại. ,
chuyể n hế t toàn b ộ các tên từ Listbox Trái sang Listbox
Phải và ngược lại.
btnXoa: cho phép xóa các tên đang chọ n trong Listbox Trái. Code: 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 SW3Basic_Controls2 { public partial class Bai3_frmListSV : Form { public Bai3_frmListSV() { InitializeComponent(); } private void tbnNhap_Click( object sender, EventArgs e) { if (txtNhap.Text != "" "") ) lsbLopA.Items.Add(txtNhap.Text); txtNhap.Text = "" ""; ; txtNhap.Focus(); } private void Bai3_frmListSV_Load( Bai3_frmListSV_Load(object object sender, EventArgs e) { txtNhap.Focus(); } private void btnChonSangB_Click( btnChonSangB_Click(object object sender, EventArgs e) {
//if(lsbLopA.SelectedIndex==-1) // MessageBox.Show("Chua MessageBox. Show("Chua chon du lieu"); while (lsbLopA.SelectedIndex!=-1) { lsbLopB.Items.Add(lsbLopA lsbLopB.Items.Add(lsbLopA.SelectedIte .SelectedItem); m); lsbLopA.Items.Remove(lsbL lsbLopA.Items.Remove(lsbLopA.Selected opA.SelectedItem); Item); } } private void btnTatCaSangB_Click(object btnTatCaSangB_Click(object sender, EventArgs e) { //if(lsbLopA.SelectedIndex==-1) // MessageBox.Show("Chua MessageBox. Show("Chua chon du lieu"); while (lsbLopA.Items.Count (lsbLopA.Items.Count > 0) { lsbLopA.SetSelected(0, true true); ); lsbLopB.Items.Add(lsbLopA lsbLopB.Items.Add(lsbLopA.SelectedIte .SelectedItem); m); lsbLopA.Items.Remove(lsbL lsbLopA.Items.Remove(lsbLopA.Selected opA.SelectedItem); Item); } } private void btnChonSangA_Click(object btnChonSangA_Click(object sender, EventArgs e) { //if(lsbLopB.SelectedIndex==-1) // MessageBox.Show("Chua MessageBox. Show("Chua chon du lieu"); while (lsbLopB.SelectedIndex (lsbLopB.SelectedIndex != -1) { lsbLopA.Items.Add(lsbLopB lsbLopA.Items.Add(lsbLopB.SelectedIte .SelectedItem); m); lsbLopB.Items.Remove(lsbL lsbLopB.Items.Remove(lsbLopB.Selected opB.SelectedItem); Item); } } private void btnTatCaVeA_Click( object sender, EventArgs e) { //if(lsbLopB.SelectedIndex==-1) // MessageBox.Show("Chua MessageBox. Show("Chua chon du lieu"); while (lsbLopB.Items.Count (lsbLopB.Items.Count > 0) { lsbLopB.SetSelected(0, true true); ); lsbLopA.Items.Add(lsbLopB lsbLopA.Items.Add(lsbLopB.SelectedIte .SelectedItem); m); lsbLopB.Items.Remove(lsbL lsbLopB.Items.Remove(lsbLopB.Selected opB.SelectedItem); Item); } } } }
Execution Result:
Bài 4: Viết chương trình từ điể từ điể n Anh – Việt và Việt – Anh (dùng TabControl) using using using using using using using using using
System; System.Collections.Generic; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms;
namespace SW3Basic_Controls2 { public partial class Bai4_frmTuDien : Form { private Dictionary Dictionary< > anhViet = new Dictionary< Dictionary(); >(); private Dictionary Dictionary< > vietAnh = new Dictionary Dictionary< (); >(); public Bai4_frmTuDien() { InitializeComponent(); initDicAnhViet(); } private void initDicAnhViet() { anhViet.Add("hello" anhViet.Add("hello", , "xin chao"); chao"); anhViet.Add("computer" anhViet.Add("computer", , "may tinh"); tinh"); anhViet.Add("win" anhViet.Add("win", , "chien thang"); thang"); //tao tap hop luu tru tu khoa tieng anh Dictionary< Dictionary . >.KeyCollection KeyCollection keyColl = anhViet.Keys; anhViet.Keys; //day tu khoa tieng anh vao combobox anhviet foreach (string s in keyColl) cmbAnhViet.Items.Add(s);
} private void cmbAnhViet_SelectedIndexChanged( cmbAnhViet_SelectedIndexChanged(object object sender, EventArgs e) { lsbAnhViet.Items.Clear(); if (cmbAnhViet.SelectedIndex (cmbAnhViet.SelectedIndex != -1) lsbAnhViet.Items.Add(anhViet[(string lsbAnhViet.Items.Add(anhViet[( string)cmbAnhViet.SelectedItem]); )cmbAnhViet.SelectedItem]); } } }
Execution Result:
Chương 4: Bài 2: Viết chương trình hiể n thị vào PictureBox lá cờ tương ứ ng ng với nước
được chọn trên Radio Button tương ứ ng. ng.
Code: 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 S4Basic_Controls3 { public partial class Bai1_frmQuocGia : Form { private ImageList imagelist = new ImageList ImageList(); (); public Bai1_frmQuocGia() { InitializeComponent(); initImageList(); } private void initImageList() { //imagelist.ImageSize(40 //imagelist. ImageSize(400, 0, 400); imagelist.ImageSize imagelist.ImageSize = new Size Size(256,256); (256,256); imagelist.Images.Add(Image.FromFile( imagelist.Images.Add(Image .FromFile(@"C:\Users\Hungbu\Dropbox\hoctap\win @"C:\Users\Hungbu\Dropbox\hoctap\win 1\thucHanh\S4Basic_Control 1\thucHanh\S4 Basic_Controls3\Bai1_images\ s3\Bai1_images\vietnam.jpg" vietnam.jpg")); )); imagelist.Images.Add(Image imagelist.Images.Add( Image.FromFile( .FromFile(@"C:\Users\Hungbu\Dropbox\hoctap\win @"C:\Users\Hungbu\Dropbox\hoctap\win 1\thucHanh\S4Basic_Control 1\thucHanh\S4 Basic_Controls3\Bai1_images\ s3\Bai1_images\lao.jpg" lao.jpg")); )); imagelist.Images.Add(Image imagelist.Images.Add( Image.FromFile( .FromFile(@"C:\Users\Hungbu\Dropbox\hoctap\win @"C:\Users\Hungbu\Dropbox\hoctap\win 1\thucHanh\S4Basic_Control 1\thucHanh\S4 Basic_Controls3\Bai1_images\ s3\Bai1_images\usa.jpg" usa.jpg")); )); imagelist.Images.Add(Image imagelist.Images.Add( Image.FromFile( .FromFile(@"C:\Users\Hungbu\Dropbox\hoctap\win @"C:\Users\Hungbu\Dropbox\hoctap\win 1\thucHanh\S4Basic_Control 1\thucHanh\S4 Basic_Controls3\Bai1_images\ s3\Bai1_images\singapore.jp singapore.jpg" g")); )); } private void radioButton1_CheckedChanged( radioButton1_CheckedChanged(object object sender, EventArgs e) { //pictureBox1.ImageLocation = "//Bai1_Images/vietnam.jpg"; //Bitmap myImage = new Bitmap(@"D:\Execrises\c#\t Bitmap(@"D:\E xecrises\c#\thucHanh\S4Basic hucHanh\S4Basic_Controls3\Bai _Controls3\Bai1_images\viet 1_images\vietnam.jpg"); nam.jpg");
//pictureBox1.Image = (Image)myImag //pictureBox1.Image (Image)myImage; e; //pictureBox1.Image //pictureBox 1.Image = pictureBox1.InitialImage; pictureBox1.InitialImage; pictureBox1.Image pictureBox1.Image = imagelist.Images[0]; imagelist.Images[0]; } private void radioButton3_CheckedChanged( radioButton3_CheckedChanged(object object sender, EventArgs e) { pictureBox1.Image pictureBox1.Image = imagelist.Images[2]; imagelist.Images[2]; } private void radioButton4_CheckedChanged( radioButton4_CheckedChanged(object object sender, EventArgs e) { pictureBox1.Image pictureBox1.Image = imagelist.Images[1]; imagelist.Images[1]; } private void radioButton5_CheckedChanged( radioButton5_CheckedChanged(object object sender, EventArgs e) { pictureBox1.Image pictureBox1.Image = imagelist.Images[3]; imagelist.Images[3]; } } }
Execution Result:
Bài 3: Tạo giao diện như hình: 2 trackbar hoặ c HscrollBar và VscrollBar (minimunvalue=50, maximumvalue=chi ề ều dài hoặc chi ề ều rộng của Form), 1 PictureBox (xuấ t hiện vị trí bắt đầu là (50,50)).
Khi người dùng thay đổ i giá trị trên thanh trượ t của Trackbar ho ặc scrollbar thì hình sẽ di chuyể n theo tọa độ tương ứ ng ng với giá trị thay
đổi trên Trackbar hoặc ScrollBar
Code: 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 S4Basic_Controls3 { public partial class Bai3_frmTrackBar : Form { public Bai3_frmTrackBar() { InitializeComponent(); } private void trackBar2_Scroll(object trackBar2_Scroll(object sender, EventArgs e) { pictureBox1.Location pictureBox1.Location = new Point Point(trackBar1. (trackBar1.Value, Value, trackBar2.Size.Height trackBar2.Size.Height trackBar2.Value+trackBar trackBar2.Value+trackBar2.Minimum); 2.Minimum); } private void trackBar1_Scroll(object trackBar1_Scroll(object sender, EventArgs e) { pictureBox1.Location pictureBox1.Location = new Point Point(trackBar1. (trackBar1.Value, Value, trackBar2.Size.Height trackBar2.Size.Height trackBar2.Value+trackBar trackBar2.Value+trackBar2.Minimum); 2.Minimum); } private void Bai3_frmTrackBar_Load( Bai3_frmTrackBar_Load(object object sender, EventArgs e) { pictureBox1.Location pictureBox1.Location = new Point Point(60, (60, 60); trackBar1.Maximum trackBar1.Maximum = this this.Width .Width - 100; trackBar2.Maximum trackBar2.Maximum = this this.Height .Height - 100; trackBar2.Value trackBar2.Value = trackBar2.Maximum; trackBar2.Maximum; } } }
Execution Result:
Bài 4: Xây dựng chương trình hiể n thị lịch tờ như sau:
Khi mới mở Form sẽ hiể n thị lịch theo ngày hiện hành. Khi thay đổ i
ngày, tháng , năm trên form (nhớ kiể m tra ngày hợp lệ) sau đó click nút Xem Lịch thì sẽ hiể n thị đúng ngày tháng năm đó vào groupbox bên phải (bao g ồm cả thứ trong tu ần).
Code: 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 S4Basic_Controls3 { public partial class Bai4_frmLich : Form { private bool isNamNhuan = false false; ; //private int[] thang; private int int[] [] soNgayTrongThang; soNgayTrongThang; public Bai4_frmLich() { InitializeComponent(); initBien(); } private void initBien() { //thang = new int[12] {1,2,3,4,5,6, {1,2,3,4,5,6,7,8,9,10,11, 7,8,9,10,11,12}; 12}; soNgayTrongThang soNgayTrongThang = new int int[12] [12] {31,28,31,30,31,30,31,31, {31,28,31,30,31,30,31,31,30,31,30,31 30,31,30,31 }; } private void numericUpDown3_ValueChanged( numericUpDown3_ValueChanged(object object sender, EventArgs e) { } private void numericUpDown1_ValueChanged( numericUpDown1_ValueChanged(object object sender, EventArgs e) { //kiem tra xem nam co nhuan hay khong //neu nhuan thi thang 2 co 29 ngay //khong nhuan thi thang 2 co 28 ngay int nam = (int (int)numericUpDown1.Value; )numericUpDown1.Value; if (nam % 4 == 0) isNamNhuan = true true; ; if (nam % 100 == 0 && nam % 400 == 0) isNamNhuan = true true; ; if (isNamNhuan) soNgayTrongThang[1] soNgayTrongThang[1] = 29; numericUpDown3.Maximum numericUpDown3.Maximum = soNgayTrongThang[( soNgayTrongThang[(int int)numericUpDo )numericUpDown2.Value wn2.Value - 1]; } private void numericUpDown2_ValueChanged( numericUpDown2_ValueChanged(object object sender, EventArgs e) { if (isNamNhuan) soNgayTrongThang[1] soNgayTrongThang[1] = 29; numericUpDown3.Maximum numericUpDown3.Maximum = soNgayTrongThang[( soNgayTrongThang[(int int)numericUpDo )numericUpDown2.Value wn2.Value - 1]; } private void button1_Click( object sender, EventArgs e) { int nam = (int (int)numericUpDown1.Value; )numericUpDown1.Value; int thang = (int (int)numericUpDown2.Value; )numericUpDown2.Value;
int ngay = (int (int)numericUpDown3.Value; )numericUpDown3.Value; DateTime dt = new DateTime DateTime(nam, (nam, thang, ngay); label4.Text = "Thang " + dt.Month.ToString(); dt.Month.ToString(); label5.Text = "Ngay " + dt.Day.ToString(); dt.Day.ToString(); label6.Text = dt.DayOfWeek.ToString(); dt.DayOfWeek.ToString(); } } }
Execution Result:
Bài 5: Viết chương trình Quản lý Đăng ký Khách hàng VIP cho Siêu thị
CoopMark như sau: Khi khách hàng đăng ký thông tin khách hàng VIP, nhân viên quả n lý khách hàng th ự c hiện nhập mã số KH, họ tên, ngày sinh, đị a ch ỉ, ngh ề nghiệp của khách.
Chương trình thự c hiện: Xây dự ng ng class KhachHang (msKH, tenKH, Ngaysinh, Diachi, NgheNghiep)
Xây dự ng ng class DanhSachKhachHang để quản lý Thêm Khách Hàng vào danh sách khách hàng thân thi ế t, t, xem t ổng số khách hàng trong danh sách. - Form_Load: Danh Sách khách hàng chưa có thành viên nào, con trỏ văn bản đặt vào textbox mã s ố khách hàng, các button Dangky, NhapMoi, TongKet b ị mờ (enabled=false). Th ự c hiện nhập các thông tin tương ứ ng. ng. Khi nhập đầy đủ thông tin (kiể m tra dữ liệu hợp lệ) thì btnDangky có tác d ụng. - btnDangKy: th ự c hiện thêm khách hàng vào Danh sách khách
hàng, đồng thời hiể n thị thông tin khách hàng v ừa đăng ký thành công vào messagebox như hình bên dướ i. btnNhapMoi, btnTongKet . - btnNhapMoi: khởi tạo lại trạng thái ban đầ u của Form, btnNhapMoi bị mờ. - btnTôngKet: hiể n thị Tổng khách hàng có trong Danh sách
khách hàng vào messagebox như hình bên dướ i. btnTongKet b ị mờ. - btnThoat_Click: hỏi người dùng có chắc chắn thoát khỏi chương trình hay không? Yes: thoát, No: không.
Danh sách các giá tr ị trong DomainUpDown Ngh ề Nghiệp:
Code: Bai5_DSKhachHang.cs using using using using using
System; System.Collections; System.Collections.Generic; System.Linq; System.Text;
namespace S4Basic_Controls3 { class Bai5_DSKhachHang { private ArrayList data; public Bai5_DSKhachHang() { data = new ArrayList ArrayList(); (); } public void ThemKhachHang(Bai5_KhachHang ThemKhachHang(Bai5_KhachHang kh) { try { data.Add(kh); } catch { throw new Exception Exception(); (); } } public int XemTongSoKH() { return data.Count; } /* public override string ToString() { foreach (object obj in data) { Bai5_KhachHang Bai5_KhachHa ng kh = (Bai5_KhachHa (Bai5_KhachHang)obj; ng)obj; return kh.ToString();
} return null; }*/ } }
Bai5_KhachHang.cs using using using using
System; System.Collections.Generic; System.Linq; System.Text;
namespace S4Basic_Controls3 { class Bai5_KhachHang { private int maKH; private string tenKH; private DateTime ngaySinh; private string diaChi; private string ngheNghiep; public Bai5_KhachHang() { } public Bai5_KhachHang(int Bai5_KhachHang(int maKH, string tenKH, DateTime ngaySinh, string diaChi, string ngheNghiep) { this.maKH this .maKH = maKH; this.tenKH this .tenKH = tenKH; this.ngaySinh this .ngaySinh = ngaySinh; this.diaChi this .diaChi = diaChi; this.ngheNghiep this .ngheNghiep = ngheNghiep; } /* public override string ToString() { return "ma khach hang: " + maKH.ToString() + "\nten khach hang: " + tenKH.ToString() + "\ngay sinh: " + ngaySinh.ToString() + "\nDia chi: " + diaChi.ToString() + "\nnghe nghiep: " + ngheNghiep.ToString(); } */ //properties } }
Execution
Result:
Chương 5: Bài 1: Tạo giao diện như hình: Khi Form Load thì có dòng ch ữ “TTĐT “TTĐT CNTT TPHCM Xin chào các bạn” chạy ngang màn hình (dùng timer)
Code: using using using using using using
System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Linq;
using System.Text; using System.Windows.Forms; namespace SW5_AdvancedControl { public partial class Bai1_frmChuChay : Form { public Bai1_frmChuChay() { InitializeComponent(); } private void Bai1_frmChuChay_Load( Bai1_frmChuChay_Load(object object sender, EventArgs e) { timChuChay.Start(); //Dispose(); } private void timChuChay_Tick( object sender, EventArgs e) { if (labelX1.Location.X (labelX1.Location.X >= ( this this.Right .Right - this this.Left)) .Left)) labelX1.Location labelX1.Location = new Point Point( (this this.Left-labelX1.Size.Width, .Left-labelX1.Size.Width, labelX1.Location.Y); else labelX1.Location labelX1.Location = new Point Point(labelX1.Lo (labelX1.Location.X cation.X + 1, labelX1.Location.Y); } } }
Execution Result:
Bài 2: Tạo Giao diem Form Splash như hình: chứ a thanh progress bar, và một nút OK. Khi khởi động chương trình thì Form Splash xuấ t hiện, và form này dừ ng ng 1 khoảng thời gian là 15s.
- Thanh progress bar s ẽ thể hiện tiế n trình load form này, sau 15s form splash sẽ tự độ ự động tắt và khởi động Form trong bài 1 - Trong khi Form Splash đang hoạt độ ng, nếu người dùng nhấ n vào nút OK thì Form này ngưng hoạt động, đồ ng thời Form bài 1 được gọi hoạt động.
Code: 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 SW5_AdvancedControl { public partial class Bai2_frmLoadSlash : Form { public Bai2_frmLoadSlash() { InitializeComponent(); } private void progressBarX1_Click( progressBarX1_Click(object object sender, EventArgs e) { } private void timer1_Tick( object sender, EventArgs e) { if (progressBarX1.Value (progressBarX1.Value == progressBarX1.Maximum) progressBarX1.Maximum) {
timer1.Stop(); Bai1_frmChuChay frm = new Bai1_frmChuChay Bai1_frmChuChay(); (); frm.Show(); this.Close(); this .Close(); } else { progressBarX1.PerformStep(); } } private void Bai2_frmLoadSlash_Load( Bai2_frmLoadSlash_Load(object object sender, EventArgs e) { progressBarX1.Minimum progressBarX1.Minimum = 0; progressBarX1.Maximum progressBarX1.Maximum = 15; progressBarX1.Step = 1; timer1.Interval timer1.Interval = 1000; timer1.Start(); } private void buttonX1_Click(object buttonX1_Click(object sender, EventArgs e) { timer1.Stop(); Bai1_frmChuChay frm = new Bai1_frmChuChay Bai1_frmChuChay(); (); frm.ShowDialog(); this.Close(); this .Close(); } } }
Chương 6: Bài 1:
Viết chương trình nhậ p danh danh b ạ với yêu c ầu giao diện như
hình dưới.
Khi chương trình vừ a hiể n thị, treeview chứ a tấ t cả các chữ cái từ A->Z.
Nhằm mục đích tiện lợi cho người sử dụng khi tìm tên, khi ngườ i sử dụng nhập tên của một người nàp đó, chương trình sẽ đưa
tên người này vào treeview ở vị trí treenode có tương ứ ng ng với chữ các ữ các đầu của tên (xem hình).
Code: using using using using using using using
System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms;
namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object Form1_Load(object sender, EventArgs e) {
// txtTen.Focus(); } private void btnNhap_Click( object sender, EventArgs e) { if (txtHo.Text != "" & txtTen.Text != "" "") ) { string hoten = txtTen.Text + ", " + txtHo.Text; foreach(TreeNode value in trvHoTen.Nodes) foreach( if (string string.Compare(value.Text.ToUpper(), .Compare(value.Text.ToUpper(), txtTen.Text[0].ToString().ToUpper()) == 0) { value.Nodes.Add(hoten); value.Expand(); txtTen.Text = txtHo.Text = "" ""; ; txtTen.Focus(); return; return ; } } } } }
Execution Result:
Bài 2:
Viết chương trình nhập dữ liệu vào Listview như hình bên dướ i.
Người sử dụng nhập thông tin: (lastname, firstname, phone) và sử dụng nút Add Name để nhập vào listview.
Các contact có biểu tượng (icon) hiể n thị như hình.
Người sử dụng có thể thay ể thay đổi chế độ ế độ view của listview bằng menu View.
Menu FormatListview hiể u thị hộp thọai chọn màu dùng để thay
đổi dạng grid của Listview. Gợi ý: o
Sử dụng ListviewItem để thêm một dòng mới cho Listview
o
Sử dụng ImageList để chứa thư viện icon cho Listview. K ế ết nố i Listview với ImageList.
Code: using using using using using using using
System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms;
namespace WindowsApplication1 { public partial class Bai2_Detail : Form { public Bai2_Detail() { InitializeComponent(); } private void Bai2_Detail_Load(object Bai2_Detail_Load(object sender, EventArgs e) { InitLsvDetail(); txtLastName.Select(); } private void InitLsvDetail() { ImageList imgList = new ImageList ImageList(); (); imgList.ColorDepth imgList.ColorDepth = ColorDepth ColorDepth.Depth4Bit; .Depth4Bit; imgList.ImageSize imgList.ImageSize = new Size Size(16, (16, 16); imgList.Images.Add(Image imgList.Images.Add( Image.FromFile( .FromFile(@"E:\IMAGES\thongoc.jpg" @"E:\IMAGES\thongoc.jpg")); )); ImageList imgListLarge = new ImageList ImageList(); (); imgListLarge.Transparent imgListLarge.TransparentColor Color = Color Color.White; .White; imgListLarge.ColorDepth imgListLarge.ColorDepth = ColorDepth ColorDepth.Depth24Bit; .Depth24Bit; imgListLarge.ImageSize imgListLarge.ImageSize = new Size Size(64,64); (64,64); imgListLarge.Images.Add(Image imgListLarge.Images.Add( Image.FromFile( .FromFile(@"E:\IMAGES\thongoc.jpg" @"E:\IMAGES\thongoc.jpg")); )); ColumnHeader clhFirstName clhFirstName = new ColumnHeader (); ColumnHeader clhLastName = new ColumnHeader ColumnHeader(); (); ColumnHeader clhPhone = new ColumnHeader (); clhFirstName.Text clhFirstName.Text = "FirstName" "FirstName"; ; clhLastName.Text clhLastName.Text = "LastName" "LastName"; ; clhPhone.Text clhPhone.Text = "PhoneNumber" "PhoneNumber"; ; clhFirstName.Width clhFirstName.Width = lsvDetail.Width lsvDetail.Width / 3-1; clhLastName.Width clhLastName.Width = lsvDetail.Width lsvDetail.Width / 3-1; clhPhone.Width clhPhone.Width = lsvDetail.Width lsvDetail.Width / 3-1; 3 -1; lsvDetail.Columns.Add(cl lsvDetail.Columns.Add(clhLastName); hLastName); lsvDetail.Columns.Add(cl lsvDetail.Columns.Add(clhFirstName); hFirstName); lsvDetail.Columns.Add(clhPhone); lsvDetail.View lsvDetail.View = View View.Details; .Details; lsvDetail.SmallImageList lsvDetail.SmallImageList = imgList; lsvDetail.LargeImageList = imgListLarge; lsvDetail.AllowColumnReo lsvDetail.AllowColumnReorder rder = true true; ; } private void lagerIconsToolStripMenuI lagerIconsToolStripMenuItem_Click( tem_Click(object object sender, EventArgs e) { lsvDetail.View lsvDetail.View = View View.LargeIcon; .LargeIcon; } private void btnNhap_Click( object sender, EventArgs e) { ListViewItem item = new ListViewItem ListViewItem(); (); item.ImageIndex item.ImageIndex = 0; item.Text = txtLastName.Text; txtLastName.Text;
item.SubItems.Add(txtFir item.SubItems.Add(txtFirstName.Text); stName.Text); //item.SubItems.Add(txtL //item.SubIt ems.Add(txtLastName.Text) astName.Text); ; item.SubItems.Add(txtPhone.Text); lsvDetail.Items.Add(item); txtFirstName.Text txtFirstName.Text = txtLastName.Text txtLastName.Text = txtPhone.Text txtPhone.Text = "" ""; ; txtLastName.Focus(); } private void detailToolStripMenuItem_Click( detailToolStripMenuItem_Click(object object sender, EventArgs e) { lsvDetail.View lsvDetail.View = View View.Details; .Details; } private void listToolStripMenuItem_Click( listToolStripMenuItem_Click(object object sender, EventArgs e) { lsvDetail.View lsvDetail.View = View View.List; .List; } private void titleToolStripMenuItem_Click( titleToolStripMenuItem_Click(object object sender, EventArgs e) { lsvDetail.View lsvDetail.View = View View.Tile; .Tile; } private void smallIconsToolStripMenuI smallIconsToolStripMenuItem_Click( tem_Click(object object sender, EventArgs e) { lsvDetail.View lsvDetail.View = View View.SmallIcon; .SmallIcon; } private void formatListVToolStripMenu formatListVToolStripMenuItem_Click( Item_Click(object object sender, EventArgs e) { } private void colorForLisviewGrapToolS colorForLisviewGrapToolStripMenuItem tripMenuItem_Click( _Click(object object sender, EventArgs e) { ColorDialog colorDialog = new ColorDialog ColorDialog(); (); //colorDialog.ShowDialog(); colorDialog.AllowFullOpe colorDialog.AllowFullOpen n = false false; ; //colorDialog.Color= } //property //private ImageList imgList; } }
Execution Result:
Bài 3: Thiế t k ế chương ế chương trình quản lý SV, cho phép nh ập thông tin SV vào các textbox Yêu c ầu:
Thêm vào form ilsNho là Imagelist có kìch thước mặc định 16 x 16 phục vụ cho ListView, ilsLon là Imagelist có kìch thướ c mặc 48 x 48 phục vụ cho ListView
Nhấ n nút C ập nhật Item thì đưa thông tin sinh viên vào Listview theo nguyên t ắc dự a theo hình.
Nhấn nút Xóa item là xóa item đang chọ n trên Listview ( có th ể chọn nhi ều), ều), nhưng phả i cài bẫy lỗi xác nhận lại tình trạng xóa. Xác nhận đã chọn Item nào chưa, xác nhậ n có chắc xóa không.
Nhấ n nút thêm m ới thì xóa thông tin sinh viên cho phép nh ập thông tin Sinh Viên m ới.
Nế u chọn một Sinh Viên nào trong Listview thì hiện lại thông tin
Sinh Viên đó lên các Texbox tương ứ ng ng .
Code using using using using
System; System.Collections.Generic; System.Text; System.Runtime.Serialization;
namespace WindowsApplication1
{ [Serializable Serializable] ] class Bai3_ThongTInSV { public string maSV; public string hoTen; public string diaChi; public string ngaySinh; public string lop; public Bai3_ThongTInSV() { } } }
: using using using using using using using using using using using
System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms; System.IO; System.Runtime.Serialization; System.Runtime.Serializa System.Runtime.Serialization.Formatte tion.Formatters.Binary; rs.Binary; System.Collections;
namespace WindowsApplication1 { //[Serializable] public partial class Bai3_ThongTinSinhVien : Form { private List List< arrSV; public Bai3_ThongTinSinhVien() { arrSV = new List List< (); >(); InitializeComponent(); InitListView(); } private void InitListView() { lsvDetail.Columns.Add("Ma lsvDetail.Columns.Add( "Ma SV", SV", lsvDetail.Width/5, lsvDetail.Width/5, HorizontalAlignment.Center); HorizontalAlignment .Center); lsvDetail.Columns.Add("Ho lsvDetail.Columns.Add( "Ho Ten SV", SV", lsvDetail.Width HorizontalAlignment.Center); HorizontalAlignment .Center); lsvDetail.Columns.Add("Dia lsvDetail.Columns.Add( "Dia Chi", Chi", lsvDetail.Width / HorizontalAlignment.Center); HorizontalAlignment .Center); lsvDetail.Columns.Add("Ngay lsvDetail.Columns.Add( "Ngay Sinh", Sinh", lsvDetail.Width HorizontalAlignment.Center); HorizontalAlignment .Center); lsvDetail.Columns.Add("Lop" lsvDetail.Columns.Add( "Lop", , lsvDetail.Width / 5, HorizontalAlignment.Center); HorizontalAlignment .Center); lsvDetail.View lsvDetail.View = View View.Details; .Details; lsvDetail.GridLines lsvDetail.GridLines = true true; ; } private void Bai3_ThongTinSinhVien_Load( Bai3_ThongTinSinhVien_Load(object object sender, {
/ 5, 5, / 5,
EventArgs e)
} private void btnThemMoi_Click(object btnThemMoi_Click(object sender, EventArgs e) { ListViewItem item = new ListViewItem ListViewItem(); (); item.Text = txtMaSV.Text; txtMaSV.Text; item.SubItems.Add(txtHoTen.Text); item.SubItems.Add(txtDia item.SubItems.Add(txtDiaChi.Text); Chi.Text); item.SubItems.Add(dtpNga item.SubItems.Add(dtpNgaySinh.Text); ySinh.Text); item.SubItems.Add(cbbLop.Text); lsvDetail.Items.Add(item); arrSV.Add(item); } private void btnLuuFile_Click(object btnLuuFile_Click(object sender, EventArgs e) { FileStream file = new FileStream FileStream( ("luu.txt" "luu.txt", , FileMode FileMode.Create); .Create); BinaryFormatter bforn = new BinaryFormatter BinaryFormatter(); (); bforn.Serialize(file, bforn.Serialize(file, arrSV); file.Close(); } private void button1_Click( object sender, EventArgs e) { FileStream file = new FileStream FileStream( ("luu.txt" "luu.txt", , FileMode FileMode.Open); .Open); BinaryFormatter bform = new BinaryFormatter BinaryFormatter(); (); arrSV.Clear(); arrSV=(List arrSV=(List< )bform.Deserialize(file); >)bform.Deserialize(file); lsvDetail.Clear(); file.Close(); foreach (ListViewItem item in arrSV) lsvDetail.Items.Add(item); lsvDetail.Update(); } } }
Execution Result:
Bài 5: Tạo 1 chương trình dùng để duyệt và hiể n thị tấ t cả các ảnh trong 1
thư mục ở dạng thumnails view.
Khi chương trình khởi độ ng sẽ nạp cây thư mụ c lên Treeview
Khi người dùng chọn 1 thư mục trên Treeview, chương trình sẽ liệt kê tấ t cả các hình ảnh lên 1 FlowlayoutPanel.
Khi người dùng chọn 1 hình t ừ FlowlayoutPanel, hình ảnh đó sẽ hiện thị lên 1 PictureBox ở phía trên
Gợi ý:
Dùng mảng picturebox động để chứ a danh sách các hình ảnh
Dùng FlowLayoutPanel để chứ a mảng picturebox
Code: using using using using using using using using
System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms; System.IO;
namespace WindowsApplication1 { public partial class Bai6_frmPlayPicture : Form { public Bai6_frmPlayPicture() { InitializeComponent(); InitExploreTreeview(); } private void InitExploreTreeview() { explorerTreeView.ShowRoo explorerTreeView.ShowRootLines tLines = true true; ; explorerTreeView.ShowLin explorerTreeView.ShowLines es = true true; ; TreeNode root; string[] string [] driver = Directory Directory.GetLogicalDrives(); .GetLogicalDrives(); foreach (string dvr in driver) {
root = new TreeNode TreeNode(dvr); (dvr); root.Nodes.Add(new root.Nodes.Add(new TreeNode TreeNode( ("" "")); )); explorerTreeView.Nodes.Add(root); } } private void toolStrip1_ItemClicked( toolStrip1_ItemClicked(object object sender, ToolStripItemClickedEventArgs e) { } private void Bai6_frmPlayPicture_Load( Bai6_frmPlayPicture_Load(object object sender, EventArgs e) { showPicPictureBox.SizeMo showPicPictureBox.SizeMode de = PictureBoxSizeMode PictureBoxSizeMode.Zoom; .Zoom; contentPicFlowLayoutPane contentPicFlowLayoutPanel.BorderStyle l.BorderStyle = BorderStyle BorderStyle.FixedSingle; .FixedSingle; } private void explorerTreeView_AfterSelect( explorerTreeView_AfterSelect(object object sender, TreeViewEventArgs e) { DirectoryInfo dir = new DirectoryInfo DirectoryInfo(e.Node.FullPath); (e.Node.FullPath); contentPicFlowLayoutPane contentPicFlowLayoutPanel.Controls.Cl l.Controls.Clear(); ear(); PictureBox[] PictureBox [] pic; showPicPictureBox.Image showPicPictureBox.Image = null null; ; if (dir.Exists) { pic = new PictureBox PictureBox[dir.GetFiles().GetLength(0)]; [dir.GetFiles().GetLength(0)]; int i = 0; foreach (FileInfo file in dir.GetFiles()) { if (file.Name.EndsWith( (file.Name.EndsWith("jpg" "jpg") ) || file.Name.EndsWith( file.Name.EndsWith("gif" "gif") ) || file.Name.EndsWith("bmp" file.Name.EndsWith( "bmp")) )) { pic[i] = new PictureBox PictureBox(); (); pic[i].Name = "pic" + file.Name; pic[i].SizeMode pic[i].SizeMode = PictureBoxSizeMode .Zoom; pic[i].Size = new Size Size(100, (100, 100); pic[i].BorderStyle pic[i].BorderStyle = BorderStyle BorderStyle.FixedSingle; .FixedSingle; pic[i].Image = Image Image.FromFile(e.Node.FullPath+ .FromFile(e.Node.FullPath+"//" "//"+file.Name); +file.Name); pic[i].Click+=new pic[i].Click+=new EventHandler (Bai6_frmPlayPicture_Click); contentPicFlowLayoutPanel contentPicFlowLayoutPanel.Controls.Ad .Controls.Add(pic[i]); d(pic[i]); i++; contentPicFlowLayoutPanel contentPicFlowLayoutPanel.Update(); .Update(); } } //MessageBox.Show(i.ToString()+", "+contentPicFlowLayoutPa "+contentPi cFlowLayoutPanel.Controls nel.Controls.Count); .Count); } } private void Bai6_frmPlayPicture_Click( Bai6_frmPlayPicture_Click(object object sender, EventArgs e) { PictureBox pic = (PictureBox (PictureBox)sender; )sender; showPicPictureBox.Image showPicPictureBox.Image = pic.Image; } private void explorerTreeView_BeforeExpand( explorerTreeView_BeforeExpand(object object sender, TreeViewCancelEventArgs e) { try {
if (e.Node.Nodes[0].Text (e.Node.Nodes[0].Text == "" "") ) { e.Node.Nodes.Clear(); FillNode(e.Node); } } catch (Exception ex) { MessageBox.Show(ex.Message); MessageBox .Show(ex.Message); } } private void FillNode(TreeNode FillNode(TreeNode rootNode) { DirectoryInfo dir = new DirectoryInfo DirectoryInfo(rootNode.FullPath); (rootNode.FullPath); foreach (DirectoryInfo chirldName in dir.GetDirectories()) { TreeNode chirldNode = new TreeNode TreeNode(chirldName.Name); (chirldName.Name); chirldNode.Nodes.Add(new chirldNode.Nodes.Add( new TreeNode TreeNode( ("" "")); )); rootNode.Nodes.Add(chirldNode); } } } }
Execution Result:
Chương 7 Bài 1: Thiế t k ế ế và lập trình cho chương trình Calculator đơn giản trong windows. (chú ý: dùng sự kiện các phím khi nhập biể u thứ c tính)
Code: 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 S7_Mouse_keyboard_handling { public partial class Bai1_Calculator : Form { private char phepToan; private float soA, soB, ketQua; public Bai1_Calculator() { InitializeComponent(); } private void Bai1_Calculator_KeyPress( Bai1_Calculator_KeyPress(object object sender, KeyPressEventArgs e) { char c = e.KeyChar; //if(hienThiText.Text) //MessageBox.Show(e.KeyC //MessageBox .Show(e.KeyChar.ToString( har.ToString()); )); if (c == '+' || c == '-' || c == '*' || c == '/' '/') ) { soA = float float.Parse(hienThiText.Text); .Parse(hienThiText.Text); phepToan=c;
hienThiText.Text hienThiText.Text = "" ""; ; } if (c == '=' '=') ) { //MessageBox.Show(e.KeyCh //MessageBox .Show(e.KeyChar.ToString( ar.ToString()); )); if(hienThiText.Text.Length==0) if (hienThiText.Text.Length==0) hienThiText.Text="0" hienThiText.Text="0"; ; soB = float float.Parse(hienThiText.Text); .Parse(hienThiText.Text); hienThiText.Text hienThiText.Text = "" ""; ; try { ketQua = Tinh(soA, soB, phepToan); hienThiText.Text hienThiText.Text = ketQua.ToString(); ketQua.ToString(); } catch (Exception ex) { hienThiText.Text = ex.Message; } } if (hienThiText.Text (hienThiText.Text == "0" "0") ) hienThiText.Text hienThiText.Text = "" ""; ; if( if (char char.IsDigit(e.KeyChar)||e.KeyChar== .IsDigit(e.KeyChar)||e.KeyChar=='.' '.') ) hienThiText.Text hienThiText.Text += c; } private float Tinh(float Tinh(float soA, float soB, char phepToan) { if (phepToan == '+' '+') ) return (soB + soA); if (phepToan == '-' '-') ) return (soA - soB); if (phepToan == '*' '*') ) return (soA * soB); if (phepToan == '/' '/') ) { try { return (soA / soB); } catch (DivideByZeroException DivideByZeroException) ) { throw new Exception Exception( ("loi chi chia cho 0.."); 0.." ); } } return 0; } private void Bai1_Calculator_Load( Bai1_Calculator_Load(object object sender, EventArgs e) { //hienThiText.Text = "0"; //hienThiText.ReadOnly = true; this.Focus(); this .Focus(); } private void Bai1_Calculator_KeyDown( Bai1_Calculator_KeyDown(object object sender, KeyEventArgs e) { } } }
Execution Result:
Bài 2: Viết chương trình thực hiện việc thực hành đánh máy chữ, giao diện
như hình bên. Yêu cầu : Khi nhấn 1 kí tự hoặt 1 số nào thì kí tự hoặt số đó chuyển sang màu đỏ, khi thả phím ra thì màu chữ trở lại màu đen. Đồng thời ký tự vừa được nhấn sẽ hiện bên dưới Text box.
Code: using System; using System.Collections.Generic;
using using using using using using using
System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Linq; System.Text; System.Windows.Forms;
namespace S7_Mouse_keyboard_handling { public partial class Bai2_frmTyper : Form { private ArrayList arrKey; public Bai2_frmTyper() { arrKey = new ArrayList ArrayList(); (); InitializeComponent(); InitLabelKey(); } private void Bai2_frmTyper_Load( Bai2_frmTyper_Load(object object sender, EventArgs e) { } private { int int int
void InitLabelKey() indexOfKey = 65; keyWidth = keyPanel.Width / 10; keyHeight = keyPanel.Height / 3;
for (int i = 0; i < 26; i++) { Label key = new Label Label(); (); key.AutoSize = false false; ; key.BorderStyle key.BorderStyle = BorderStyle BorderStyle.Fixed3D; .Fixed3D; key.Font = new Font Font( (new FontFamily FontFamily( ("Arial" "Arial"), ), 15f, FontStyle FontStyle.Bold); .Bold); key.TextAlign key.TextAlign = ContentAlignment ContentAlignment.MiddleCenter; .MiddleCenter; key.Parent = this this.keyPanel; .keyPanel; key.Text = char char.ConvertFrom .ConvertFromUtf32(indexO Utf32(indexOfKey).ToUpper fKey).ToUpper(); (); //key.Tag if (i < 10) key.Location = new Point Point((i%10) ((i%10) * keyWidth, 1); else if (i>=10&&i<20) key.Location = new Point Point((i%10) ((i%10) * keyWidth, 1 + keyHeight); else key.Location = new Point Point((i ((i % 10) * keyWidth, 1 + 2*keyHeight); key.Width = keyWidth; key.Height = keyHeight; keyPanel.Controls.Add(key); arrKey.Add(key); indexOfKey++; } } private void noiDungRichTextBox_KeyPress( noiDungRichTextBox_KeyPress(object object sender, KeyPressEventArgs e) { //for (int i = 0; i < 26; i++) //{ // if (Char.Parse (Char.Parse(((Label)arrK (((Label)arrKey[i]).Text) ey[i]).Text) == e.KeyChar) // { // ((Label)arrKey[i]).ForeCo ((Label)arrK ey[i]).ForeColor lor = Color.Red;
// keyPanel.Update(); // return; // } //} foreach (Control ctr in keyPanel.Controls) { if (String String.Compare(ctr. .Compare(ctr.Text.ToUpper Text.ToUpper(),e.KeyChar. (),e.KeyChar.ToString().T ToString().ToUpper())==0) oUpper())==0) { ctr.ForeColor ctr.ForeColor = Color Color.Red; .Red; keyPanel.Update(); return; return ; } } //keyPanel.Refresh(); } private void noiDungRichTextBox_KeyUp( noiDungRichTextBox_KeyUp(object object sender, KeyEventArgs e) { foreach (Control ctr in keyPanel.Controls) { ctr.ForeColor ctr.ForeColor = this this.ForeColor; .ForeColor; } keyPanel.Update(); } } }
Execution Result:
Chương 9: Bài 1: Tạo giao diện Form như hình:
Viết code cho các menu tương ứ ng: ng: Form treeview: - Tạo giao diện như hình, cho phép ngườ i dùng nhập vào treeview các
node có định dạng như hình. - Tạo contextmenustrip áp dụng cho treeview, để thao tác trự c tiế p
ngay trên treeview như: đổ i tên, xóa node, xóa t ấ t cả các node trên treeview. - Viế t các code thích hợp cho các menu c ủa contextmenustrip
Form Listview: ( bài tập 3, chương 6) - Tạo giao diện như hình, cho phép ngườ i dùng nhập vào ListView các ph ần tử có ử có định dạng như hình. - Tạo contextmenustrip áp dụng cho Listview, để thao tác tr ự c tiế p
ngay trên ListView như: Large Icon, Small, List, Tile, Detail, Update (cập nhật lại thông tin của ph ần tử ) - Viế t các code thích hợp cho các menu c ủa contextmenustrip
Code: 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 S9_Menu_Toolbar_Status { public partial class Bai1_MDIForm : Form { //private Container container; public Bai1_MDIForm() { InitializeComponent(); } private void treeViewToolStripButton_Click( treeViewToolStripButton_Click(object object sender, EventArgs e) { Bai1_TreeViewChirld treeFrm = new Bai1_TreeViewChirld Bai1_TreeViewChirld(); (); treeFrm.MdiParent treeFrm.MdiParent = this this; ; treeFrm.Text = "Tree View Chirld.."; Chirld.." ; //container.Add(treeFrm); //this.MdiParent.comp treeFrm.Show(); }
private void toolStrip1_ItemClicked( toolStrip1_ItemClicked(object object sender, ToolStripItemClickedEventArgs e) { } private void Bai1_MDIForm_Load( object sender, EventArgs e) { this.IsMdiContai this .IsMdiContainer ner = true true; ; this.WindowState this .WindowState = FormWindowState FormWindowState.Maximized; .Maximized; } private void listViewToolStripButton_Click( listViewToolStripButton_Click(object object sender, EventArgs e) { WindowsApplication1.Bai3_ThongTinSinhVien WindowsApplication1. Bai3_ThongTinSinhVien thongTinSV = new WindowsApplication1.Bai3_ThongTinSinhVien WindowsApplication1. Bai3_ThongTinSinhVien(); (); thongTinSV.MdiParent thongTinSV.MdiParent = this this; ; thongTinSV.Text thongTinSV.Text = "List View Chirld.."; Chirld.." ; //container.Add(thongTinSV); thongTinSV.Show(); } private void cascadeToolStripMenuItem_Click( cascadeToolStripMenuItem_Click(object object sender, EventArgs e) { this.LayoutMdi( this .LayoutMdi(MdiLayout MdiLayout.Cascade); .Cascade); } private void tiToolStripMenuItem_Click( tiToolStripMenuItem_Click(object object sender, EventArgs e) { this.LayoutMdi( this .LayoutMdi(MdiLayout MdiLayout.TileVertical); .TileVertical); } private void arrangeIconsToolStripMen arrangeIconsToolStripMenuItem_Click( uItem_Click(object object sender, EventArgs e) { this.LayoutMdi( this .LayoutMdi(MdiLayout MdiLayout.ArrangeIcons); .ArrangeIcons); } private void closeAllToolStripMenuItem_Click( closeAllToolStripMenuItem_Click(object object sender, EventArgs e) { //this.MdiParent.Contain //this.MdiPa rent.Container.Dispose(); er.Dispose(); //this.MdiParent.Close(); foreach (Form frmChirld in this this.MdiChildren) .MdiChildren) { frmChirld.Close(); } } private void exitToolStripMenuItem_Click( exitToolStripMenuItem_Click(object object sender, EventArgs e) { this.Close(); this .Close(); } } } using using using using using using using
System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Text; System.Windows.Forms;
namespace WindowsApplication1 { public partial class Bai3_ThongTinSinhVien : Form { public Bai3_ThongTinSinhVien() { InitializeComponent(); } private void Bai3_ThongTinSinhVien_Load( Bai3_ThongTinSinhVien_Load(object object sender, EventArgs e) { txtMaSV.Select(); } private void largeIconToolStripMenuIt largeIconToolStripMenuItem_Click( em_Click(object object sender, EventArgs e) { lsvDetail.View lsvDetail.View = View View.LargeIcon; .LargeIcon; } private void detailToolStripMenuItem_Click( detailToolStripMenuItem_Click(object object sender, EventArgs e) { lsvDetail.View lsvDetail.View = View View.Details; .Details; } private void smallToolStripMenuItem_Click( smallToolStripMenuItem_Click(object object sender, EventArgs e) { lsvDetail.View lsvDetail.View = View View.SmallIcon; .SmallIcon; } private void listToolStripMenuItem_Click( listToolStripMenuItem_Click(object object sender, EventArgs e) { lsvDetail.View lsvDetail.View = View View.List; .List; } private void titleToolStripMenuItem_Click( titleToolStripMenuItem_Click(object object sender, EventArgs e) { lsvDetail.View lsvDetail.View = View View.Tile; .Tile; } private void updateToolStripMenuItem_Click( updateToolStripMenuItem_Click(object object sender, EventArgs e) { } } } 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 S9_Menu_Toolbar_Status { public partial class Bai1_TreeViewChirld : Form { public Bai1_TreeViewChirld() { InitializeComponent();
} private void nhapButton_Click(object nhapButton_Click(object sender, EventArgs e) { if (maSoText.Text.Length (maSoText.Text.Length != 0) { TreeNode node = new TreeNode TreeNode(maSoText.Text); (maSoText.Text); if (!treeView1.Nodes.Contai (!treeView1.Nodes.Contains(node)) ns(node)) { TreeNode parentNode = treeView1.Nodes.Add(maSoText.Text); int parentIndex = treeView1.Nodes.IndexOf(pa treeView1.Nodes.IndexOf(parentNode); rentNode); treeView1.Nodes[parentInd treeView1.Nodes[parentIndex].Tag ex].Tag = "parent" "parent"; ; treeView1.Nodes[parentInd treeView1.Nodes[parentIndex].Nodes.Ad ex].Nodes.Add(hoTenText.T d(hoTenText.Text); ext); treeView1.Nodes[parentInd treeView1.Nodes[parentIndex].Nodes.Ad ex].Nodes.Add(diaChiText. d(diaChiText.Text); Text); treeView1.Nodes[parentInd treeView1.Nodes[parentIndex].Nodes.Ad ex].Nodes.Add(lopText.Tex d(lopText.Text); t); treeView1.Nodes[parentInd treeView1.Nodes[parentIndex].Expand() ex].Expand(); ; } else { MessageBox.Show( MessageBox .Show("trung "trung ma so.."); so.."); //break; } } else MessageBox.Show( MessageBox .Show("ma "ma so khong duoc rong.."); rong.." ); maSoText.Text maSoText.Text = hoTenText.Text hoTenText.Text = diaChiText.Text diaChiText.Text = lopText.Text = "" ""; ; maSoText.Focus(); } private void removeToolStripMenuItem_Click( removeToolStripMenuItem_Click(object object sender, EventArgs e) { TreeNode node = treeView1.SelectedNode; treeView1.SelectedNode; if (node.Tag.ToString() (node.Tag.ToString() != "parent" "parent") ) node = node.Parent; treeView1.Nodes.Remove(node); } private void renameNodeToolStripMenuI renameNodeToolStripMenuItem_Click( tem_Click(object object sender, EventArgs e) { treeView1.LabelEdit treeView1.LabelEdit = true true; ; TreeNode node = treeView1.SelectedNode; treeView1.SelectedNode; node.BeginEdit(); //node.EndEdit( } private void removeAllNodeToolStripMe removeAllNodeToolStripMenuItem_Click nuItem_Click( ( object sender, EventArgs e) { treeView1.Nodes.Clear(); } } }
Execution Result:
Bài 2:
Tạo 1 trình duyệt đơn giản như sau:
ToolBar: Các nút GoBack, Go Forward, Refresh, Stop và Home , URL
bar, Go button. (dùng ToolStrip để tạo hint cho các nút trên Toolbar)
Control Webbrowser: để hiể n thị nội dung của trang web
Status bar: chèn thêm 1 progressbar để theo dõi tiế n trình download trang web.
Execution Result:
Chương 10: Bài 1: 1. Xây dự ng ng UserControl Login giao diện thiế t k ế như ế như hình
- Validation các textBox not blank. -
Xử lý mã cứ ng ng user name và password
-
User control ném ra 2 event : LoginSuccess và LoginFail.
-
Đưa Control vào ToolBox với icon tùy chọn.
2. Xây dựng chương trình sử dụng UserControl với giao diện như sau :
Code: using using using using using using using using
System; System.Collections.Generic; System.ComponentModel; System.Drawing; System.Data; System.Linq; System.Text; System.Windows.Forms;
namespace S10_CommonDialog_CustomControl { public partial class Bai1_LoginUserControl : UserControl { //event handler public EventHandler LoginSuccess; public EventHandler LoginFail; public Bai1_LoginUserControl() { InitializeComponent(); } //properties public string UserNameLabel { get { return lbUsername.Text; lbUsername.Text; } set { lbUsername.Text = value value; ; } } public string PasswordLabel { get { return lbPassword.Text; lbPassword.Text; } set { lbPassword.Text = value value; ; } }
public string LoginButton { get { return btnLogin.Text; btnLogin.Text; } set { btnLogin.Text = value value; ; } } [Browsable Browsable( (false false)] )] //khong cho phep nhap text trong luc thiet ke public string UserName { set { txtUsername.Text = value value; ; } } [Browsable Browsable( (false false)] )] public string PassWord { set { txtPassword.Text = value value; ; } } //login button click handler private void btnLogin_Click(object btnLogin_Click(object sender, EventArgs e) { if (txtUsername.Text.Length (txtUsername.Text.Length == 0){ MessageBox.Show( MessageBox .Show("enter "enter user name.."); name.." ); return; return ; } if (txtPassword.Text.Length (txtPassword.Text.Length == 0) { MessageBox.Show( MessageBox .Show("enter "enter pass word.."); word.." ); return; return ; } if (AllVali(txtUsername.Text, (AllVali(txtUsername.Text, txtPassword.Text)) txtPassword.Text)) { if (LoginSuccess != null null) ) LoginSuccess(this LoginSuccess(this, , EventArgs EventArgs.Empty); .Empty); } else if (LoginFail != null null) ) LoginFail(this LoginFail(this, , EventArgs EventArgs.Empty); .Empty); } private bool AllVali(string AllVali( string uName, string pWord) { return (uName == "admin" && pWord == "ngochung" "ngochung"); ); } } } 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 S10_CommonDialog_CustomControl { public partial class Bai1_UserCOntrol : Form { private string useName = "admin" "admin"; ; private string pass = "ngochung" "ngochung"; ; public Bai1_UserCOntrol() { InitializeComponent();
} private void btnLogin_Click(object btnLogin_Click(object sender, EventArgs e) { if (txtUsername.Text (txtUsername.Text != "" && txtPassword.Text != "" "") ) { if (string string.Compare(txtUsername.Text, .Compare(txtUsername.Text, useName) == 0 && string.Compare(tx string .Compare(txtPassword.Te tPassword.Text, xt, pass) == 0) { //nem ra event success //tao MessageBox.Show( MessageBox .Show("ban "ban dang nhap thanh cong..."); cong..." ); } else { //nem ra event fail MessageBox.Show( MessageBox .Show("dang "dang nhap khong thanh cong..."); cong..." ); } txtUsername.Text = txtPassword.Text = "" ""; ; txtUsername.Focus(); } else { MessageBox.Show( MessageBox .Show("phai "phai nhap username va password.."); password.." ); txtUsername.Focus(); } } private void Bai1_UserCOntrol_Load( Bai1_UserCOntrol_Load(object object sender, EventArgs e) { txtUsername.Select(); } } }
Execution Result:
Bài 2: 1. Xây dự ng ng form OutFit Details giao diện thiế t k ế như ế như hình
-
Nhấ n Next hay Previous s ẽ đi qua sản phẩ m k ế ế tiếp hay trước đó.
để báo đã đi tới record cuối hay record đầu ( không di - Validation để báo chuyển được nữ a) a)
-
Khi bấ m Print sẽ in ra PrintPreviewDialog bằng các API GDI + ;
-
Gợi ý: o
Khai báo một class chứ a sản phẩ m (Description, MyPicture)
o
Khai báo 1 ArrayList arr chứ a các sản phẩ m
o
Nhập 5 Sản phẩ m vào arr
Code: using using using using using using
System; System.Collections.Generic; System.Linq; System.Text; System.Windows.Forms; System.Drawing;
namespace S10_CommonDialog_CustomControl { class Bai3_OutFitClass { private string moTa; private Image hinhAnh; public Bai3_OutFitClass(string Bai3_OutFitClass(string mt, Image ha)
{ MoTa = mt; HinhAnh = ha; } public string MoTa { get { return moTa; } set { moTa = value value; ; } } public Image HinhAnh { get { return hinhAnh; } set { hinhAnh = value value; ; } } } } using using using using using using using using using using
System; System.Collections.Generic; System.Collections; System.ComponentModel; System.Data; System.Drawing; System.Drawing.Printing; System.Linq; System.Text; System.Windows.Forms;
namespace S10_CommonDialog_CustomControl { public partial class Bai3_OutFitDetail : Form { private ArrayList arrOutFit; private int count = 0; public Bai3_OutFitDetail() { InitializeComponent(); arrOutFit = new ArrayList ArrayList(); (); InitArrOutFit(); ptbOutFit.SizeMode ptbOutFit.SizeMode = PictureBoxSizeMode PictureBoxSizeMode.Zoom; .Zoom; txtMoTa.Text = ((Bai3_OutFitClass (( Bai3_OutFitClass)arrOutFit[count]).MoTa; )arrOutFit[count]).MoTa; ptbOutFit.Image ptbOutFit.Image = ((Bai3_OutFitClass ((Bai3_OutFitClass)arrOutFit[count]).HinhAnh; )arrOutFit[count]).HinhAnh; } private void InitArrOutFit() { Bai3_OutFitClass outFit1 = new Bai3_OutFitClass Bai3_OutFitClass( ("outfit 1", 1", Image.FromFile( Image .FromFile("images/1.jpg" "images/1.jpg")); )); Bai3_OutFitClass outFit2 = new Bai3_OutFitClass Bai3_OutFitClass( ("outfit 2", 2", Image.FromFile( Image .FromFile("images/2.jpg" "images/2.jpg")); )); Bai3_OutFitClass outFit3 = new Bai3_OutFitClass Bai3_OutFitClass( ("outfit 3", 3", Image.FromFile( Image .FromFile("images/3.jpg" "images/3.jpg")); )); Bai3_OutFitClass outFit4 = new Bai3_OutFitClass Bai3_OutFitClass( ("outfit 4", 4", Image.FromFile( Image .FromFile("images/4.jpg" "images/4.jpg")); )); arrOutFit.Add(outFit1); arrOutFit.Add(outFit1); arrOutFit.Add(outFit2); arrOutFit.Add(outFit2); arrOutFit.Add(outFit3); arrOutFit.Add(outFit3); arrOutFit.Add(outFit4); } private void btnNext_Click( object sender, EventArgs e) { if (count < 0) count = 0;
if (count < 3) { count++; txtMoTa.Text = "" ""; ; txtMoTa.Text = ((Bai3_OutFitClass (( Bai3_OutFitClass)arrOutFit[count]).MoTa; )arrOutFit[count]).MoTa; ptbOutFit.Image ptbOutFit.Image = ((Bai3_OutFitClass ((Bai3_OutFitClass)arrOutFit[count]).HinhAnh; )arrOutFit[count]).HinhAnh; } } private void btnPre_Click(object btnPre_Click(object sender, EventArgs e) { if (count > 3) count=3; if (count > 0) { count--; txtMoTa.Text = "" ""; ; txtMoTa.Text = ((Bai3_OutFitClass (( Bai3_OutFitClass)arrOutFit[count]).MoTa; )arrOutFit[count]).MoTa; ptbOutFit.Image ptbOutFit.Image = ((Bai3_OutFitClass ((Bai3_OutFitClass)arrOutFit[count]).HinhAnh; )arrOutFit[count]).HinhAnh; } } private void btnPrint_Click(object btnPrint_Click(object sender, EventArgs e) { PrintPreviewDialog printPreview = new PrintPreviewDialog PrintPreviewDialog(); (); PrintDocument doc = new PrintDocument PrintDocument(); (); doc.PrintPage doc.PrintPage += new PrintPageEventHandler PrintPageEventHandler(PrintDoc); (PrintDoc); printPreview.Document printPreview.Document = doc; doc.DocumentName doc.DocumentName = "Test GDI+"; GDI+"; printPreview.ShowDialog(); } private void PrintDoc(object PrintDoc(object sender, PrintPageEventArgs e) { Image im = ptbOutFit.Image; string des = txtMoTa.Text; e.Graphics.DrawString(des, new Font Font( ("Arial" "Arial",30f), ,30f), new SolidBrush( SolidBrush (Color Color.Red), .Red), new Point Point(20, (20, 20)); e.Graphics.DrawImage(im, new Point Point(120, (120, 120)); } } }
Execution Result:
Bài 3: Xây dựng chương trình Wordpad đơn giản như hình bên dướ i: Sử dụng các Commond dialog: SaveFileDialog, OpenFileDialog, ColorDialog, FontDialog
Code: using using using using using using using using using using
System; System.Collections.Generic; System.ComponentModel; System.Data; System.Drawing; System.Drawing.Printing; System.Linq; System.Text; System.IO; System.Windows.Forms;
namespace S10_CommonDialog_CustomControl { public partial class Bai4_Notepad : Form { public Bai4_Notepad() { InitializeComponent(); } private void fontToolStripButton_Click( fontToolStripButton_Click(object object sender, EventArgs e) {
FontDialog fontDia = new FontDialog FontDialog(); (); fontDia.ShowApply fontDia.ShowApply = true true; ; fontDia.Apply fontDia.Apply += new EventHandler EventHandler(ApplyFont); (ApplyFont); fontDia.Font = noiDungRichText.Font; fontDia.Color fontDia.Color = noiDungRichText.ForeColor noiDungRichText.ForeColor; ; if (fontDia.ShowDialog() (fontDia.ShowDialog() == DialogResult .OK) { ApplyFont(fontDia, EventArgs EventArgs.Empty); .Empty); } } private void ApplyFont(object ApplyFont( object sender, EventArgs e) { FontDialog fontDia = (FontDialog ( FontDialog)sender; )sender; noiDungRichText.Font = fontDia.Font; noiDungRichText.ForeColo noiDungRichText.ForeColor r = fontDia.Color; fontDia.Color; } private void colorToolStripButton_Click( colorToolStripButton_Click(object object sender, EventArgs e) { ColorDialog colorDia = new ColorDialog ColorDialog(); (); colorDia.Color colorDia.Color = noiDungRichText.ForeColo noiDungRichText.ForeColor; r; if (colorDia.ShowDialog() (colorDia.ShowDialog() == DialogResult DialogResult.OK) .OK) { noiDungRichText.ForeColor noiDungRichText.ForeColor = colorDia.Color; colorDia.Color; } } private void printToolStripButton_Click( printToolStripButton_Click(object object sender, EventArgs e) { PrintDocument doc = new PrintDocument PrintDocument(); (); doc.PrintPage+= new PrintPageEventHandler PrintPageEventHandler(doc_PrintPage); (doc_PrintPage); PrintDialog prin = new PrintDialog PrintDialog(); (); if (prin.ShowDialog() (prin.ShowDialog() == DialogResult DialogResult.OK) .OK) { doc.Print(); } } private void doc_PrintPage( object sender, PrintPageEventArgs e) { string s = noiDungRichText.Text; e.Graphics.DrawString(s, new Font Font( ("Arial" "Arial", , 13f), new SolidBrush( SolidBrush (Color Color.Red), .Red), new Point Point(20, (20, 20)); } private void openToolStripButton_Click( openToolStripButton_Click(object object sender, EventArgs e) { OpenFileDialog openFile = new OpenFileDialog (); openFile.Filter openFile.Filter = "Text file|*.txt"; file|*.txt"; if (openFile.ShowDialog() (openFile.ShowDialog() == DialogResult DialogResult.OK) .OK) { Stream myStream = openFile.OpenFile(); openFile.OpenFile(); StreamReader streamReader = new StreamReader (myStream); noiDungRichText.Text noiDungRichText.Text = streamReader.ReadToEnd(); streamReader.ReadToEnd(); streamReader.Close(); myStream.Close(); } } private void newToolStripButton_Click( newToolStripButton_Click(object object sender, EventArgs e) { noiDungRichText.Text noiDungRichText.Text = "" ""; ; }
private void saveToolStripButton_Click( saveToolStripButton_Click(object object sender, EventArgs e) { SaveFileDialog saveFile = new SaveFileDialog (); saveFile.Filter saveFile.Filter = "Text file|*.txt"; file|*.txt"; if (saveFile.ShowDialog() (saveFile.ShowDialog() == DialogResult DialogResult.OK) .OK) { Stream myStream = saveFile.OpenFile(); saveFile.OpenFile(); StreamWriter myWriter = new StreamWriter (myStream); myWriter.Write(noiDungRic myWriter.Write(noiDungRichText.Text); hText.Text); myWriter.Close(); myStream.Close(); } } } }