Common Language Runtime (CLR)
Common Type System (CTS) toàn
.NET Framework Common Type System (CTS)
1.2.4 Biên d ch và MS Intermediate Language
Trong NET Framewor build project Mã MSIL này
Garbage collection -
Namespace
System.Console.WriteLine( Hello C Sharp ); using System;
CÁC NGÔN C#
Các lo
Hình 1.8: using System; using System.Collections.Generic; using System.Text;
In ra câu chào "Hello World" */ using System; namespace HelloWorld { class Program
{ static void Main(string[] args)
The article provides a comprehensive overview of various data types in programming, detailing their names, corresponding CTS types, sizes, and value ranges For instance, the sbyte type (System.SByte) has a size of 8 bits and a range from -128 to 127, while the short type (System.Int16) is 16 bits with a range of -32768 to 32767 The int type (System.Int32) spans 32 bits, accommodating values from -2^31 to 2^31 - 1, and the long type (System.Int64) extends to 64 bits with a range of -2^63 to 2^63 - 1 Additionally, the byte type (System.Byte) is 8 bits with a range of 0 to 255, and the ushort type (System.UInt16) is 16 bits ranging from 0 to 65535 The uint type (System.UInt32) covers 32 bits with values from 0 to 2^32 - 1, while the ulong type (System.UInt64) is 64 bits with a range of 0 to 2^64 - 1 The article also mentions floating-point types such as float (System.Single) and double (System.Double), as well as the decimal type (System.Decimal) which is 128 bits Lastly, it includes boolean (System.Boolean) and character (System.Char) types, with char being 16 bits.
2abc, Chuong-Trinh, Xu Ly, class khô
ChuongTrinh và chuongtrinh là khác nhau
NGÔN C#
Ch
Float b = Float.Parse( 20.7 bool c = Boolean.Parse( true int a = Int32.Parse( Hello byte b = Byte.Parse( 10000000000 boolc = Boolean.Pars
Boolean.TryParse( false , out b); //b s bool c = Boolean.TryParse(
1.4.5.3 Convert int a = Convert.ToInt32( 123 bool a = Convert.ToBoolean( khoaimon ); //FormatException int b = Convert.ToInt32( 123456787654 ); //OverflowException double d = Convert.ToDouble
{ break; case gi break; break; default: break;
Cú pháp: foreach (var item in collection )
- string[] thuTT = { Hai , Ba , , , S u , B y , Ch Nh t };
//khai b o m ng chu i c c ph n t ki c c ngày trong tu n int[] myInteger = new int[5];
List thuTTList = new List {"Ba", , ,"Sáu", "B y"}; thuTTList.Add( ); thuTTList.Insert(0, "Hai");
//T int size = thuTTList.Count; thuTTList.Sort(); foreach(string s in thuTTList)
Console.WriteLine(today); // Output: Wednesday
1.4.5.13 Khai báo và x lý ki u d li u
- var: ta var number = 2023; var name = ; var myList = new List();
"nullable type" int? number = null;
Câu 1: football, do, get, set, basketball
Khuôn mẫu trong ngành công nghiệp sản xuất đóng vai trò quan trọng trong việc tạo ra các sản phẩm chất lượng cao Để đáp ứng nhu cầu của thị trường, các nhà sản xuất cần thiết kế khuôn mẫu phù hợp với loại sản phẩm cụ thể Việc tối ưu hóa quy trình sản xuất và lựa chọn nguyên liệu chất lượng sẽ giúp nâng cao hiệu suất và giảm thiểu lãng phí Sự kết hợp giữa thiết kế khuôn mẫu và quy trình sản xuất hiệu quả sẽ đảm bảo cung cấp sản phẩm đáp ứng tiêu chuẩn của người tiêu dùng.
Trong lập trình ngôn ngữ C#, bạn cần phân nhánh các khuôn mẫu cần thiết để sản xuất ra các sản phẩm đáp ứng nhu cầu của mình Trong minh họa trên, hết nhấn mạnh là nguyên lý tạo ra sản phẩm là những nguyên liệu chính, trong đó nguyên liệu chính là dữ liệu Dữ liệu thực chất có kiểu dữ liệu nguyên thủy (Primitive data type) mà C# cung cấp, có thể là những kiểu dữ liệu khác nhau.
Trong quá trình xây dựng Class cho game, cần thiết kế dựa trên những nguyên lý nhất định Mỗi nhân vật trong game, như chiến binh, cần có chiều cao, cân nặng, hình dạng và giá trị sức mạnh riêng biệt Để đảm bảo tính đa dạng, các thuộc tính (properties) của từng nhân vật và phương tiện cũng cần được xác định rõ ràng Class xe hơi phải có những nguyên liệu cần thiết, trong khi Class chiến binh cần xây dựng các thuộc tính như chiều cao, cân nặng và hình dáng khác nhau để tạo nên sự phong phú cho trò chơi.
Mỗi loại xe có thể di chuyển khác nhau trên mỗi loại hình, và mỗi loại xe có thể khác nhau khi vào các tình huống khác nhau Class xeHoi là phương thức chính cho các loại xe này Mỗi chiến binh có thể khác nhau, có thể cao hoặc thấp, và điều này ảnh hưởng đến class chienBinh.
Khi xây d ng class trong C#, b n ph nh ngh a c c properties c ng v i method c n thi c th s d ng c a m nh.
Khai báo
[access modifier] class [: base class]
[access modifier] ;
- access modifier: 4 protected, internal, private khai báo là Internal) o p o i
Đoạn mã dưới đây định nghĩa một lớp `HocSinh` trong ngôn ngữ lập trình C# Lớp này chứa các thuộc tính quan trọng để quản lý thông tin của học sinh, bao gồm mã học sinh (`_maHS`), họ tên (`_hoTen`), giới tính (`_gioiTinh`), và số điện thoại (`_soDT`) Các thuộc tính này được khai báo với kiểu dữ liệu tương ứng: `int` cho mã học sinh, `string` cho họ tên, `bool` cho giới tính (với giá trị mặc định là false), và `long` cho số điện thoại.
Constructor
Destructor
Method
ngoài , là tatic và non static
{ public CSharp() { //} public static void StaticMethod() { //} public void NonStaticMethod() { //} public static void Main()
CSharp cs = new CSharp(); cs.NonStaticMethod();
2.1.6 N p ch ng (method overload) class Calculator
{ public int Add(int num1, int num2)
} public double Add(double num1, double num2)
} public int Add(int num1, int num2, int num3)
Calculator calculator = new Calculator(); int result1 = calculator.Add(2000, 23);
Console.WriteLine( + result1); double result2 = calculator.Add(3.14, 3.2);
Console.WriteLine( + result2); int result3 = calculator.Add(1, 2, 4);
2.1.7 Thu c tính (Property) getter/setter ra tính class Circle
42 private double radius; public double Radius
} ô Circle circle = new Circle(); circle.Radius = 3.5;
Console.WriteLine("Bán kính: " + circle.Radius);
Th a k trong l p tr ng cho ph p b n c th t o ra 1 l p m i c t t c nh ng t nh ch t v c c a 1 l c m không ph i vi t l i b t c 1 d ng l nh n o, và ngoài ra cho phép vào các thà
VÀ HÌNH
Up-cast và down-cast
: is using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Data; namespace Test
44 protected string name; public string Name
{ get { return name; } set { name = value; }
STUDENT s2 = (STUDENT)h2; if (h2 is STUDENT)
// Can kiem tra s1 co khac null khong, truoc khi tiep tuc su dung s1 if (s1 != null)
//** Abstract class public abstract class Employee
//Khai báo Properties public abstract String ID
Public abstract String Add(); public virtual String Update()
{ private string id; public override String ID
{ get { return id; } set { id = value; }
// Neu can thay doi thi co the overrid lai, khong bat buoc
/// The main entry point for the application
// thuc thi phuong thuc Add cua lop Worker ee.Add();
//Thuc thi phuong thuc Employee.Update neu khong override lai phuon g thuc Update
// Hoac thuc thi phuong thuc Worker.Update() neu co override lai tai lop Worker ee.Update();
- Interface: iBay, iBoi, iChay abstract class MayMoc
- cho Class còn Interface là cho Method
- Cú pháp: [access modifier] interface [: base interface list]
I mparable, IDisposable, public interface IEmployee
//Khai báo Properties string ID
//Khai báo Method string Add(); string Update();
Interface public class Employee1 : IEmployee
{ protected String id; protected String name;
{ get { return id; } set { id = value; }
50 using System; sealed class MyClass
MyClass mC = newMyClass(); mC.x = 110; mC.y = 150;
// Ví using System; class MyClass1 { public int x; publicint y; public virtual void Method() {
Public override sealed void Method() {
} class MainClass { public static void Main() {
MyClass1 mC = newMyClass(); mC.x = 110; mC.y = 150;
Console.WriteLine( x = {0}, y = {1} , mC.x, mC.y); mC.Method();
THÁC - DELEGATE
Khai báo
Instance delegate
- cáchcác cách sau: public class TestDelegate1
{ public delegate int DoSomething(int x, int y); publicint Add(int x, int y)
DoSomething obj = delegate(int x, int y)
Multicast delegate
Cho phép add (+=) các method
Call Delegate
- using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace Test
{ public delegate void MyDelegate1(int x, int y); public delegate string MyDelegate2(float f); public void Method1(int x, int y)
MyDelegate1 del1 = new MyDelegate1(Method1); int x = 5, y = 10; del1(x, y); del1(100, y);
MyDelegate2 del2 = new MyDelegate2(Method2); string s = del2(100f);
MyDelegate1 mulDel = new MyDelegate1(Print); mulDel += new MyDelegate1(Sum); mulDel(5, 10); //Thuc thi lan luot phuong thuc Print va Sum mulDel -= new MyDelegate1(Print); mulDel(5, 10); //Thuc thi phuong thuc Sum
Demo Buble sort
- delegate bool CompareOp(object lhs, object rhs);
- static public void Sort(object [] sortArray, CompareOp gtMethod)
RhsIsGreater using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace Test
{ static public void Sort(object[] sortArray, CompareOp gtMethod) { for (int i = 0; i < sortArray.Length; i++)
{ object temp = sortArray[i]; sortArray[i] = sortArray[j]; sortArray[j] = temp;
{ private string name; private decimal salary; public Employee(string name, decimal salary)
{ this.name = name; this.salary = salary;
{ return string.Format(name + , {0:C} , salary);
} public static bool RhsIsGreater(object lhs, object rhs)
Employee empRhs = (Employee)rhs; return (empRhs.salary > empLhs.salary) ? true : false;
} delegate bool CompareOp(object lhs, object rhs); class MainEntryPoint
Employee[] employees = { new Employee( Karli Watson , 20000), new Employee( Bill Gates , 10000), new Employee( Simon Robinson , 25000), new Employee( Mortimer , (decimal)1000000.38), new Employee( Arabel Jones , 23000), new Employee( Avon from 'Blake's 7' , 50000)
CompareOp employeeCompareOp = new CompareOp(Employee.RhsIsGreater); BubbleSorter.Sort(employees, employeeCompareOp); for (int i = 0; i < employees.Length; i++)
Event
- public delegate void HandlerName(object obj, EventArgs arg);
- Khai báo event public event HandlerName OnEventName;
- using System; using System.Threading; namespace SecondChangeEvent
// Our subject it is this class that other classes will observe
// This class publishes one event : SecondChange The observers subscribe to that event public class Clock
// private Fields holding the hour, minute and second private int _hour; private int _minute; private int _second;
// The delegate named SecondChangeHandler, which will encapsulate any method
// that takes a clock object and a TimeInfoEventArgs object as the parameter and returns no value delegate the subscribers must implement. public delegate void SecondChangeHandler(object clock,
// The event we publish public event SecondChangeHandler SecondChange;
// The method which fires the event protected void OnSecondChange(object clock, TimeInfoEventArgs timeInformation)
// Check if there are any Subscribers if (SecondChange != null)
// Set the clock running, it will raise an event for each new second public void Run()
System.DateTime dt = System.DateTime.Now;
// If the second has changed
// notify the subscribers if (dt.Second != _second)
// Create the TimeInfoEventArgs object to pass to the subscribers
TimeInfoEventArgs(dt.Hour,dt.Minute,dt.Second);
// If anyone has subscribed, notify them
// The class to hold the information about the event in this case it will hold only information
// available in the clock class , but could hold additional state information public class TimeInfoEventArgs : EventArgs
{ public TimeInfoEventArgs(int hour, int minute, int second)
{ this.hour = hour; this.minute = minute; this.second = second;
} public readonly int hour; public readonly int minute; public readonly int second;
// An observer DisplayClock subscribes to the
// The job of DisplayClock is to display the current time public class DisplayClock
// Given a clock, subscribe to its SecondChangeHandler event public void Subscribe(Clock theClock)
// The method that implements the delegate d functionality public void TimeHasChanged(object theClock, TimeInfoEventArgs ti) {
Console.WriteLine( Current Time: {0}:{1}:{2} , ti.hour.ToString(), ti.minute.ToString(), ti.second.ToString());
// A second subscriber whose job is to write to a file public class LogClock
{ public void Subscribe(Clock theClock)
// This method should write to a file
// we write to the console to see the effect
// this object keeps no state public void WriteLogEntry(object theClock, TimeInfoEventArgs ti) {
Console.WriteLine( Logging to file: {0}:{1}:{2} , ti.hour.ToString(), ti.minute.ToString(), ti.second.ToString());
// Test Application which implements the Clock Notifier - Subscriber Sample public class Test
// Create the display and tell it to
// subscribe to the clock just created
DisplayClock dc = new DisplayClock(); dc.Subscribe(theClock);
// Create a Log object and tell it
// to subscribe to the clock
LogClock lc = new LogClock(); lc.Subscribe(theClock);
// Get the clock started theClock.Run();
L ANGUAGE INTEGRATED Q UERY (LINQ)
// ra các trong numbers var numQuery = from num in numbers where (num % 2) == 1 select num;
// 3 thi truy foreach (int num in numQuery)
List stringList = new List() { "C#", "Python" ,"Java" };
IEnumerable listStartC = stringList.Where(p => p.StartsWith("C")).ToList(); var context = new StudentModel();
IQueryable studentList = context.Students.Where(p => p.AverageScore > 5);
// 2 câu truy ra các trong numbers var numQuery = from num in numbers where (num % 2) == 1 select num; numbers[0] = 0;
// 3 thi truy foreach (int num in numQuery)
- hoàn int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; var numQuery (from num in numbers where (num % 2) == 1 select num).ToArray(); numbers[0] = 0; foreach (int num in numQuery)
- from select Cú pháp này có
List stringList = new List() {
// LINQ Query Syntax var result = from s in stringList where s.Contains("Tutorials") select s;
List stringList = new List() { "C# ","Python" , "Java" }; // LINQ Method syntax (lambda expression: s => s.Contains("Tutorials")) var result = stringList.Where(s => s.Contains("Tutorials")); là gì?
Toàn s => s.Contains("Tutorials") là gì? - lambda expression
Where Select, SelectMany Take, Skip, TakeWhile, SkipWhile Join, GroupJoin
ToSequence, ToArray, ToList, ToDictionary, ToLookup, OfType, Cast
First, FirstOrDefault, Last, LastOrDefault, Single, SingleOrDefault, ElementAt, ElementAtOrDefault, DefaultIfEmpty
Các hàm tính toán Count, LongCount, Sum, Min, Max, Average, Aggregate
Range, Repeat, Empty Any, All, Contains Concat namespace System.Linq string[] names = new string[]{
IEnumerable x = from n in names where n.StartsWith("T") select n; n => n.StartsWith("T"))
IEnumerable y = names.Where(n => n.StartsWith("T")); dùng cách
Select var x = from n in names select n.Length; n => n.Length) var y = names.Select(n => n.Length);
The inner join query combines two collections, `names` and `ages`, by matching their indices It utilizes LINQ syntax to create anonymous objects that include both the item and its index, allowing for a seamless join operation based on the index values The result is a selection of combined data from both collections.
2.6.2.4 Phân vùng d li u toá Skip, SkipWhile,
// #1: query syntax var x = from n in names.Skip(2) select n;
// #2: method syntax var y = names.Skip(2);
// #1: query syntax var x = from n in names.Take(2) select n;
// #2: method syntax var y = names.Take(2);
// #1: query syntax var x = from n in names orderby n.Length descending, n select n;
// #2: method syntax var y = names.OrderByDescending(n => n.Length).ThenBy(n => n);
// #1: query syntax var x = from n in names group n by n.Length;
// #2: method syntax var y = names.GroupBy(key => key.Length);
Console.WriteLine(customerGroup.Key); foreach (string i in customerGroup)
OfType: students có tên class Student
List listStudent = (from n in names select new Student() { Name = n }).ToList();
List listStudent = names.Select(s => new Student() { Name s }).ToList();
2.6.2.8 Các hàm tính toán t ng h p
// #1: query syntax var x = (from i in ages select i).Average();
// #2: method syntax var y = ages.Average();
// #1: query syntax var x = (from n in names where n.Length >= 4 select n).Count();
// #2: method syntax var y = names.Where(n=>n.Length>=4).Count();
// #1: query syntax var x = (from n in names select n).First(n=>n.StartsWith("H"));
// #2: method syntax var y = names.First(n=>n.StartsWith("H"));
// #1: query syntax var x = (from n in names select n).Distinct();
// #2: method syntax var y = ages.Distinct(); quen LINQ, chúng ta
Câu 6: IEnumerable và IQueryable là gì?
{ public string Name; public string Team; public float Score;
{ static void Main(string[] args)
To set the console output and input encoding to Unicode, use the command `Console.OutputEncoding = Console.InputEncoding = Encoding.Unicode;` A list of players can be created using the following code: `var listPlayer = new List { new Player { Name = "Anh", Team = "A", Score = 10 }, new Player { Name = "Vân", Team = "A", Score = 25 }, new Player { Name = "Player3", Team = "L", Score = 60 }, new Player { Name = "Player4", Team = "L", Score = 20 }, new Player { Name = "Player5", Team = "A", Score = 40 }, new Player { Name = "Vinh", Team = "L", Score = 30 } };`.
3.1.1 Giao di h a Graphical User Interface
- Graphical: text, window, menu, bu
3.1.2 l p trình s ki n Event-Driven Programming theo trong danh sách tính tác User-Computer
Chon Menu File -> New -> Project
FormBorderStyle = Sizable, thì form cho phép
Hình 4.6: C tính cho các TabPages
ListView myListView = new ListView(); // Khai báo ListView control myListView.Size = new System.Drawing.Size(390, 100); // Kích this.Controls.Add(myListView);
Thay i ch xem (Changing the display modes)
Hình 4.12: T Add các item vào ListView (Khi ListView không theo cách hi n th Details)
- í ào button tính Items Thì ì ào
Để thêm các mục vào myListView, bạn có thể sử dụng cú pháp như sau: myListView.Items.Add("Công Thông Tin"); myListView.Items.Add("Bách Khoa"); myListView.Items.Add("Khoa Nhiên"); myListView.Items.Add("Nhân"); myListView.Items.Add("Kinh").
Hình 4.14: L Add các vào ListView (Adding columns to the ListView) ách ách add cá ên:
- ng có myListView.Columns.Add("Tên , 200); myListView.Columns.Add( sinh viên", 100);
- ý: ó ác columns thì chú à Details myListView.View = View.Details;
Add sub Item vào Listview (Khi ListView ch xem Details)
- ách add cá trình bà úng ta click và í á
- úng ta có ác item con cho item chí ách bì ính
ListViewItem cntt = new ListViewItem("Công Thông Tin");
ListViewItem.ListViewSubItem svcntt = new ListViewItem.ListViewSubItem(cntt,
"3.000 sinh viên"); cntt.SubItems.Add(svcntt); myListView.Items.Add(cntt);
ListViewItem bk = new ListViewItem("Bách Khoa");
ListViewItem.ListViewSubItem svbk = new ListViewItem.ListViewSubItem(bk, "18.00 sinh viên"); bk.SubItems.Add(svbk); myListView.Items.Add(bk);
ListViewItem khtn = new ListViewItem("Khoa Nhiên");
ListViewItem.ListViewSubItem svkhtn = new ListViewItem.ListViewSubItem(khtn,
"20.000 sinh viên"); khtn.SubItems.Add(svkhtn); myListView.Items.Add(khtn);
ListViewItem nv = new ListViewItem("Khoa Xã & Nhân );
ListViewItem.ListViewSubItem svnv = new ListViewItem.ListViewSubItem(nv,
"15.000 sinh viên"); nv.SubItems.Add(svnv); myListView.Items.Add(nv);
ListViewItem ktl = new ListViewItem("Kinh - );
ListViewItem.ListViewSubItem svktl = new ListViewItem.ListViewSubItem(ktl,
"10.000 sinh viên"); ktl.SubItems.Add(svktl); myListView.Items.Add(ktl);
Thêm Style cho SubItems ú êm cá á ách ú ính UseItemStyleForSubItem = true; ú ác á ác nhau cho các subitems
ListViewItem ktl = new ListViewItem("Kinh - );
ListViewItem.ListViewSubItem svktl = new ListViewItem.ListViewSubItem(ktl,
"10.000 sinh viên"); ktl.SubItems.Add(svktl); myListView.Items.Add(ktl); ktl.UseItemStyleForSubItems = true;
Xóa item (Removing item) óa toà ác item trong ListView có tên là myListView.Clear();
ListViewItem cntt = new ListViewItem("Công Thông Tin"); cntt.Remove();
Liên hình danh sách các items
- ính n ng làm ê ác items trong danh sách chú ó á ày là ê ì
- ên ké ào Form (tê à imageList1)
- ào listview liê ì myListView.SmallImageList = imageList1; // Liên danh sách hình imageList1
ListViewItem cntt = new ListViewItem("Công Thông Tin", 0); ListViewItem.ListViewSubItem svcntt = new ListViewItem.ListViewSubItem(cntt,
"3.000 sinh viên"); cntt.SubItems.Add(svcntt); myListView.Items.Add(cntt);
ListViewItem bk = new ListViewItem("Bách Khoa", 1);
ListViewItem.ListViewSubItem svbk = new ListViewItem.ListViewSubItem(bk, "18.00 sinh viên"); bk.SubItems.Add(svbk); myListView.Items.Add(bk);
ListViewItem khtn = new ListViewItem("Khoa Nhiên",2);
ListViewItem.ListViewSubItem svkhtn = new ListViewItem.ListViewSubItem(khtn,
"20.000 sinh viên"); khtn.SubItems.Add(svkhtn); myListView.Items.Add(khtn);
ListViewItem nv = new ListViewItem("Khoa Xã & Nhân , 3);
ListViewItem.ListViewSubItem svnv = new ListViewItem.ListViewSubItem(nv,
"15.000 sinh viên"); nv.SubItems.Add(svnv); myListView.Items.Add(nv);
ListViewItem ktl = new ListViewItem("Kinh - , 4);
ListViewItem.ListViewSubItem svktl = new ListViewItem.ListViewSubItem(ktl,
"10.000 sinh viên"); ktl.SubItems.Add(svktl); myListView.Items.Add(ktl);
- ý 2 trong add item chính là tham hình trong imageList1
Để thêm một ListBox vào form tính tiền, ListBox này sẽ lưu trữ thông tin tính tiền của khách hàng Mỗi thông tin tính tiền sẽ được lưu trên một dòng trong ListBox, với mỗi item chứa hai thông tin: tên khách hàng.
B sung chức năng lưu trữ thông tin tính tiền của khách hàng trong một file text, trong đó mỗi dòng chứa một thông tin tính tiền bao gồm tên khách hàng và tổng số tiền.
3 B sung ch c n ng c file: cho phép load thông tin tính ti n khách hàng t m file l u tr (theo mô t trong ph n 2)
Tùy chọn tính tiền phòng nha cho phép điều chỉnh giá cho từng dịch vụ Hiện tại, giá dịch vụ là cố định, do đó chúng ta cần sử dụng tính năng này Sinh viên nên tạo file chứa bảng giá dịch vụ, thiết lập form cho phép quản lý phòng nha có thể điều chỉnh giá tiền này, lưu lại file, và mỗi lần cần chạy dịch vụ thì sử dụng file để lấy giá.
5.1.2.1 I nteroperability a nhi u h th ng khác nhau ng
5.1.2.4 Performance Hi u qu cao trong x lý d li u
ODBC Data Provider Odbc System.Data.Odbc
OleDb Data Provider OleDb System.Data OleDb
Oracle Data Provider Oracle System.Data.OracleClient
SQL Data Provider Sql System.Data.SqlClient
- using System; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Collections.Generic; public classDBAccess
{ public string cnnString ConfigurationManager.ConnectionStrings[ ConnectionString ].ConnectionString; public DBAccess()
} public DataTable GetDataTable(string query)
DataTable myData = newDataTable(); using (SqlConnection cnn = newSqlConnection(cnnString))
SqlCommand myCommand = newSqlCommand(query, cnn);
SqlDataAdapter myAdapter = newSqlDataAdapter(myCommand); myAdapter.Fill(myData);
} public string Single(string query)
{ string ret = ; using (SqlConnection cnn = newSqlConnection(cnnString))
SqlDataAdapter myAdapter = newSqlDataAdapter(query, cnn);
DataTable myData = newDataTable(); myAdapter.Fill(myData); if (myData.Rows.Count > 0)
DataRow myRow = myData.Rows[0]; ret = myRow[0].ToString();
} public bool Execute(string query)
{ bool success = false; using (SqlConnection cnn = newSqlConnection(cnnString))
SqlCommand myCommand = newSqlCommand(query, cnn); success = myCommand.ExecuteNonQuery() > 0;
SqlConnection cnn = new SqlConnection(); cnn.ConnectionString= server=.\\SQLEXPRESS;database=Northwind;
SqlCommand cmd = new SqlCommand(); cmd.CommandText = Select COUNT(*) From Customer ; cmd.Connection = cnn; cnn.Open(); int count = (int) cmd.ExecuteScalar(); cnn.Close(); rerturn count;
} public bool InsertStudent(int id, string name, DateTime birthdate, int sex, string address, int phone)
To establish a connection to the database, use the SqlConnection class with the specified connection string, which includes the server name, database name, and integrated security settings The SQL query for inserting student data into the "Sinhvien" table is defined, utilizing parameters for student ID, name, date of birth, gender, address, and phone number Finally, a SqlCommand object is created to execute the query against the established connection.
SqlParameter param = new SqlParameter( @MS , SqlDbType.Int); param.Value = id; cmd.Parameters.Add(param); cmd.Parameters.Add(new SqlParameter( @DT , phone));
//add truc tiep cmd.Parameters.Add( @HT , SqlDbType.NVarChar); cmd.Parameters.Add( @NS , SqlDbType.DateTime); cmd.Parameters.Add( @GT , SqlDbType.Bit); cmd.Parameters.Add( @DC , SqlDbType.NVarChar);
The code snippet sets parameter values for a command object, assigning the ID to `@MS`, the name to `@HT`, the birthdate to `@NS`, the sex to `@GT`, the address to `@DC`, and a fixed value of 5120791 to `@DT` A try block is initiated to handle potential exceptions during execution.
{ conn.Open(); count = (int)cmd.ExecuteNonQuery();
} finally { if (conn.State == ConnectionState.Open)
SqlCommand cmd = new SqlCommand( Select * From Sinhvien , conn); conn.Open();
SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { listBox1.Items.Add(reader[ Hoten ]);
{ string strConn = Server=.;Database=StudentDB; Trusted_connection=true ; string query = Select * From Sinhvien ;
SqlDataAdapter adapter = new SqlDataAdapter(query, strConn);
DataSet ds = new DataSet(); adapter.Fill(ds);
// thao tác trên dataset adapter.Update(ds);
- using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Data; namespace WindowsFormsApplication1
{ string strConn = Properties.Settings.Default.ConnectionString; string strCmd = SELECT * FROM Student ; public void UpdateRow()
SqlDataAdapter da = new SqlDataAdapter(strCmd, strConn);
SqlCommandBuilder builder = new SqlCommandBuilder(da);
DataSet ds = new DataSet(); da.Fill(ds); foreach (DataRow dr in ds.Tables[0].Rows) dr[ Ngaysinh ] = DateTime.Now; da.Update(ds);
SqlDataAdapter da = new SqlDataAdapter(strCmd, strConn);
SqlCommandBuilder builder = new SqlCommandBuilder(da);
DataSet ds = new DataSet(); da.Fill(ds);
DataRow[] rows = table.Select( Ngaysinh Add Project - -> New Connection -> SQL Server, AdventureWorks database -
- Build - using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace WindowsFormsApplication1
{ public partial class Form1 : Form
SqlConnection(Properties.Settings.Default.ConnectionString);
DataSet ds = new DataSet(); public Form1()
} private void Form1_Load(object sender, EventArgs e)
{ string sql = @ SELECT * FROM Employee ; da.SelectCommand = new SqlCommand(sql, conn); da.Fill(ds, Employee );
FirstnameTextBox.DataBindings.Add( Text , ds,
LastnameTextBox.DataBindings.Add( Text , ds.Tables[ Employee ], LastName );
// binding DataTable ds.Tables[ Employee ] cua ds voi dataGridView1 // Cach 1 dataGridView1.DataSource = ds; dataGridView1.DataMember = Employee ;
//dataGridView1.DataSource = ds.Tables[ Employee ];
//binnding bMgr voi DataTable Employee cua DataSet ds bMgr = this.BindingContext[ds, Employee ];
} private void button1_Click_1(object sender, EventArgs e)
{ if (bMgr.Position < ds.Tables[0].Rows.Count) bMgr.Position += 1;
} private void button2_Click_1(object sender, EventArgs e)
{ if (bMgr.Position > 0) bMgr.Position -= 1;
6.2.3 Data Binding d li u cho Windows Controls
Datasource List objects, ArrayList, A , áp
// binding DataTable ds.Tables[ Employee ] cua ds voi dataGridView1 // Cach 1 dataGridView1.DataSource = ds; dataGridView1.DataMember = Employee ; // data table name
The code snippet demonstrates how to set the data source of a DataGridView in a Windows Forms application using C# It utilizes a DataSet to bind employee data to the DataGridView, allowing for efficient display and management of database records The necessary namespaces, including System, System.Data, and System.Windows.Forms, are imported to facilitate the application's functionality.
{ public partial class Form1 : Form
SqlConnection(Properties.Settings.Default.ConnectionString);
DataSet ds = new DataSet(); public Form1()
} private void Form1_Load(object sender, EventArgs e)
{ string sql = @ SELECT * FROM Employee ; da.SelectCommand = new SqlCommand(sql, conn); da.Fill(ds, Employee );
// binding DataTable ds.Tables[ Employee ] cua ds voi dataGridView1 // Cach 1 dataGridView1.DataSource = ds; dataGridView1.DataMember = Employee ; // data table name
//dataGridView1.DataSource = ds.Tables[ Employee ];
// binding combox box voi danh sach phong ban comboBox1.DataSource = LoadDepartmentData(); comboBox1.ValueMember = ID ; comboBox1.DisplayMember = DepartmentName ;
//binnding bMgr voi DataTable Employee cua DataSet ds bMgr = this.BindingContext[ds, Employee ];
FirstnameTextBox.DataBindings.Add( Text , ds,
LastnameTextBox.DataBindings.Add( Text , ds, Employee.LastName ); comboBox1.DataBindings.Add( SelectedValue , ds,
} private void button1_Click_1(object sender, EventArgs e)
{ if (bMgr.Position < ds.Tables[0].Rows.Count) bMgr.Position += 1;
} private void button2_Click_1(object sender, EventArgs e)
{ if (bMgr.Position > 0) bMgr.Position -= 1;
SqlDataReader reader = new SqlCommand( SELECT * FROM Department , conn);
List list = new List(); conn.Open(); reader.ExecuteReader(); while (reader.Read())
Department cl = new Department(); cl.ID = reader.GetInt32(0);
138 cl.DepartmentName = reader.GetString(1); list.Add(cl);
- Các thao tác insert, update, delete trên EF
- LINQ to Entities, Entity SQL và Native SQL
7.1 ENTITY FRAMEWORK (EF) b và thao tác
7.1.1 Ki n trúc trong Entity FrameWork
7.1.1.1 T ng ng d ng (Application) qua Object Services
EDM ( mapping store schema definition
LINQ to Entity thông qua câu management system
7.1.2 Các thành ph n trong Entity FrameWork
7.2 S D NG ENTITY FRAMEWORK MÔ HÌNH
AverageScore) và mã khoa (FacultyID)
- Empty EF Designer model: cho ph
- Empty Code First model: cho p database
- Code First from database: database
Trong Code First from database và click Next
7.2.3 DBContext context trong Entity Framework
Student.cs và Faculty.cs
(Create, Read, Update, và Delete) mà
SaveChanges() using (var context = new StudentModel())
{ var f = new Faculty() { FacultyID = 100, FacultyName= "CNTT" }; context.Faculties.Add(f); //Add vào DbSet context.SaveChanges();
} using (var context = new StudentModel())
{ var s = new Student() { StudentID = "1799062090", FullNameSang", AverageScore = 7.6, FacultyID= 100}; context.Students.Add(s); //Add vào DbSet context.SaveChanges();
1799 using (var context = new StudentModel())
{ var std = context.Students.First(p => p.StudentID ="1799062090"); std.FullName = ; std.AverageScore = 8.6; context.SaveChanges();
1799062090 using (var context = new StudentModel())
{ var std = context.Students.First(p => p.StudentID ="1799062090"); context.Students.Remove(std); //Remove trong DBSet context.SaveChanges();
// #2: method syntax (lambda expression s=>s.AverageScore>=5)
List studentList = context.Students.Where(s => s.AverageScore
>= 5).ToList(); foreach (Student s in studentList)
Khoa = {3}", s.StudentID, s.FullName, s.AverageScore, s.Faculty.FacultyName);
150 using (var ctx = new StudentModel())
{ var studentList = ctx.Students.SqlQuery("SELECT * from Student WHERE AverageScore>=5").ToList();
ObjectQuery thay vì IQueryable. string sqlString = "SELECT VALUE st FROM SchoolDBEntities.Students " + "AS st WHERE st.AverageScore >= 5"; var objctx = (ctx as IObjectContextAdapter).ObjectContext;
ObjectQuery student = objctx.CreateQuery(sqlString); var studentList = student.ToList();
NHÂN VIÊN: Mã nhân viên
PHÒNG BAN Mã phòng , tên
Mô hình 3- và mô hình -
- Service Agents: n lí thành viên Presentation,
Library và Add Reference vào project GUI
8.3 MÔ HÌNH 3 L P VÀ ENTITY FRAMEWORK
- BUS: viên, khoa, chuyên ngành
3-layer và EF code first:
Câu 1: Mô hình 3-tier là gì ? Cho
Câu 5: các mô hình MVC (Model-View-
WINDOWS FORM
CÁC KHÁI
3.1.1 Giao di h a Graphical User Interface
- Graphical: text, window, menu, bu
3.1.2 l p trình s ki n Event-Driven Programming theo trong danh sách tính tác User-Computer
WINDOWS FORM
Chon Menu File -> New -> Project
WINDOWS CONTROLS
CÁC CONTROLS
Hình 4.6: C tính cho các TabPages
ListView myListView = new ListView(); // Khai báo ListView control myListView.Size = new System.Drawing.Size(390, 100); // Kích this.Controls.Add(myListView);
Thay i ch xem (Changing the display modes)
Hình 4.12: T Add các item vào ListView (Khi ListView không theo cách hi n th Details)
- í ào button tính Items Thì ì ào
Để thêm các mục vào myListView, bạn có thể sử dụng cú pháp như sau: `myListView.Items.Add("Công Thông Tin");`, `myListView.Items.Add("Bách Khoa");`, `myListView.Items.Add("Khoa Nhiên");`, `myListView.Items.Add("Nhân");`, và `myListView.Items.Add("Kinh");`.
Hình 4.14: L Add các vào ListView (Adding columns to the ListView) ách ách add cá ên:
- ng có myListView.Columns.Add("Tên , 200); myListView.Columns.Add( sinh viên", 100);
- ý: ó ác columns thì chú à Details myListView.View = View.Details;
Add sub Item vào Listview (Khi ListView ch xem Details)
- ách add cá trình bà úng ta click và í á
- úng ta có ác item con cho item chí ách bì ính
ListViewItem cntt = new ListViewItem("Công Thông Tin");
ListViewItem.ListViewSubItem svcntt = new ListViewItem.ListViewSubItem(cntt,
"3.000 sinh viên"); cntt.SubItems.Add(svcntt); myListView.Items.Add(cntt);
ListViewItem bk = new ListViewItem("Bách Khoa");
ListViewItem.ListViewSubItem svbk = new ListViewItem.ListViewSubItem(bk, "18.00 sinh viên"); bk.SubItems.Add(svbk); myListView.Items.Add(bk);
ListViewItem khtn = new ListViewItem("Khoa Nhiên");
ListViewItem.ListViewSubItem svkhtn = new ListViewItem.ListViewSubItem(khtn,
"20.000 sinh viên"); khtn.SubItems.Add(svkhtn); myListView.Items.Add(khtn);
ListViewItem nv = new ListViewItem("Khoa Xã & Nhân );
ListViewItem.ListViewSubItem svnv = new ListViewItem.ListViewSubItem(nv,
"15.000 sinh viên"); nv.SubItems.Add(svnv); myListView.Items.Add(nv);
ListViewItem ktl = new ListViewItem("Kinh - );
ListViewItem.ListViewSubItem svktl = new ListViewItem.ListViewSubItem(ktl,
"10.000 sinh viên"); ktl.SubItems.Add(svktl); myListView.Items.Add(ktl);
Thêm Style cho SubItems ú êm cá á ách ú ính UseItemStyleForSubItem = true; ú ác á ác nhau cho các subitems
ListViewItem ktl = new ListViewItem("Kinh - );
ListViewItem.ListViewSubItem svktl = new ListViewItem.ListViewSubItem(ktl,
"10.000 sinh viên"); ktl.SubItems.Add(svktl); myListView.Items.Add(ktl); ktl.UseItemStyleForSubItems = true;
Xóa item (Removing item) óa toà ác item trong ListView có tên là myListView.Clear();
ListViewItem cntt = new ListViewItem("Công Thông Tin"); cntt.Remove();
Liên hình danh sách các items
- ính n ng làm ê ác items trong danh sách chú ó á ày là ê ì
- ên ké ào Form (tê à imageList1)
- ào listview liê ì myListView.SmallImageList = imageList1; // Liên danh sách hình imageList1
ListViewItem cntt = new ListViewItem("Công Thông Tin", 0); ListViewItem.ListViewSubItem svcntt = new ListViewItem.ListViewSubItem(cntt,
"3.000 sinh viên"); cntt.SubItems.Add(svcntt); myListView.Items.Add(cntt);
ListViewItem bk = new ListViewItem("Bách Khoa", 1);
ListViewItem.ListViewSubItem svbk = new ListViewItem.ListViewSubItem(bk, "18.00 sinh viên"); bk.SubItems.Add(svbk); myListView.Items.Add(bk);
ListViewItem khtn = new ListViewItem("Khoa Nhiên",2);
ListViewItem.ListViewSubItem svkhtn = new ListViewItem.ListViewSubItem(khtn,
"20.000 sinh viên"); khtn.SubItems.Add(svkhtn); myListView.Items.Add(khtn);
ListViewItem nv = new ListViewItem("Khoa Xã & Nhân , 3);
ListViewItem.ListViewSubItem svnv = new ListViewItem.ListViewSubItem(nv,
"15.000 sinh viên"); nv.SubItems.Add(svnv); myListView.Items.Add(nv);
ListViewItem ktl = new ListViewItem("Kinh - , 4);
ListViewItem.ListViewSubItem svktl = new ListViewItem.ListViewSubItem(ktl,
"10.000 sinh viên"); ktl.SubItems.Add(svktl); myListView.Items.Add(ktl);
- ý 2 trong add item chính là tham hình trong imageList1
1 B sung m t ListBox vào form tính ti n, ListBox này dù l u tr các thông tin tính ti n c a khách hàng M i thông tin tính ti n s c l u trên m t dòng trong ListBox (m t item c a listbox) M t item g m hai thông tin: -
2 B sung ch c n ng L u: cho phép l u tr các thông tin tính ti n c a khách hàng trong m t file text File text này có nh d ng m i dòng là m t thông tin tính ti n: g tên khách hàng + t ng s ti n
3 B sung ch c n ng c file: cho phép load thông tin tính ti n khách hàng t m file l u tr (theo mô t trong ph n 2)
4 T o ch c n ng Tùy ch n: cho phé i tính ti n phòng nha có th ch h l i n giá cho t ng d ch v Hi n t ng d ng trên các n giá là fix, ta s c ti n l i ch c n ng này Sinh viên nên t o file ch a n giá t ng d ch v , t o form cho phé i qu n lý phòng nha có th hi u ch nh l i giá ti n này, l u l i file , và m i l n ng d ng ch y thì c file l y n giá.
ADO.NET
CÁC ADO.NET
DATA BINDING
CÁC
- data txtCustomer.DataBindings.Add( Text , ds.Tables[0], CustomerID );
- cbGender.DataBindings.Add( Checked , ds.Tables[0], Gender );
- có using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace WindowsFormsApplication1
{ public partial class Form1 : Form
} private void Form1_Load(object sender, EventArgs e)
{ string sql = @ SELECT * FROM Employee ;
SqlConnection(Properties.Settings.Default.ConnectionString);
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
DataSet ds = new DataSet(); da.Fill(ds, Employee );
FirstnameTextBox.DataBindings.Add( Text , ds,
LastnameTextBox.DataBindings.Add( Text , ds.Tables[ Employee ], LastName );
- Bindin sách nhân viên (ds.Tables[ Employee
-> Add Project - -> New Connection -> SQL Server, AdventureWorks database -
- Build - using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace WindowsFormsApplication1
{ public partial class Form1 : Form
SqlConnection(Properties.Settings.Default.ConnectionString);
DataSet ds = new DataSet(); public Form1()
} private void Form1_Load(object sender, EventArgs e)
{ string sql = @ SELECT * FROM Employee ; da.SelectCommand = new SqlCommand(sql, conn); da.Fill(ds, Employee );
FirstnameTextBox.DataBindings.Add( Text , ds,
LastnameTextBox.DataBindings.Add( Text , ds.Tables[ Employee ], LastName );
// binding DataTable ds.Tables[ Employee ] cua ds voi dataGridView1 // Cach 1 dataGridView1.DataSource = ds; dataGridView1.DataMember = Employee ;
//dataGridView1.DataSource = ds.Tables[ Employee ];
//binnding bMgr voi DataTable Employee cua DataSet ds bMgr = this.BindingContext[ds, Employee ];
} private void button1_Click_1(object sender, EventArgs e)
{ if (bMgr.Position < ds.Tables[0].Rows.Count) bMgr.Position += 1;
} private void button2_Click_1(object sender, EventArgs e)
{ if (bMgr.Position > 0) bMgr.Position -= 1;
6.2.3 Data Binding d li u cho Windows Controls
Datasource List objects, ArrayList, A , áp
// binding DataTable ds.Tables[ Employee ] cua ds voi dataGridView1 // Cach 1 dataGridView1.DataSource = ds; dataGridView1.DataMember = Employee ; // data table name
The code snippet demonstrates how to set the data source of a DataGridView in a Windows Forms application using C# It utilizes a DataSet to bind employee data to the DataGridView, allowing for efficient display and management of employee records within the application The necessary namespaces, including System, System.Data, and System.Windows.Forms, are imported to facilitate the functionality of the application.
{ public partial class Form1 : Form
SqlConnection(Properties.Settings.Default.ConnectionString);
DataSet ds = new DataSet(); public Form1()
} private void Form1_Load(object sender, EventArgs e)
{ string sql = @ SELECT * FROM Employee ; da.SelectCommand = new SqlCommand(sql, conn); da.Fill(ds, Employee );
// binding DataTable ds.Tables[ Employee ] cua ds voi dataGridView1 // Cach 1 dataGridView1.DataSource = ds; dataGridView1.DataMember = Employee ; // data table name
//dataGridView1.DataSource = ds.Tables[ Employee ];
// binding combox box voi danh sach phong ban comboBox1.DataSource = LoadDepartmentData(); comboBox1.ValueMember = ID ; comboBox1.DisplayMember = DepartmentName ;
//binnding bMgr voi DataTable Employee cua DataSet ds bMgr = this.BindingContext[ds, Employee ];
FirstnameTextBox.DataBindings.Add( Text , ds,
LastnameTextBox.DataBindings.Add( Text , ds, Employee.LastName ); comboBox1.DataBindings.Add( SelectedValue , ds,
} private void button1_Click_1(object sender, EventArgs e)
{ if (bMgr.Position < ds.Tables[0].Rows.Count) bMgr.Position += 1;
} private void button2_Click_1(object sender, EventArgs e)
{ if (bMgr.Position > 0) bMgr.Position -= 1;
SqlDataReader reader = new SqlCommand( SELECT * FROM Department , conn);
List list = new List(); conn.Open(); reader.ExecuteReader(); while (reader.Read())
Department cl = new Department(); cl.ID = reader.GetInt32(0);
138 cl.DepartmentName = reader.GetString(1); list.Add(cl);
ENTITY FRAMEWORK (EF)
E NTITY F RAME W ORK (EF)
7.1.1 Ki n trúc trong Entity FrameWork
7.1.1.1 T ng ng d ng (Application) qua Object Services
EDM ( mapping store schema definition
LINQ to Entity thông qua câu management system
7.1.2 Các thành ph n trong Entity FrameWork
7.2 S D NG ENTITY FRAMEWORK MÔ HÌNH
AverageScore) và mã khoa (FacultyID)
- Empty EF Designer model: cho ph
- Empty Code First model: cho p database
- Code First from database: database
Trong Code First from database và click Next
S E NTITY F RAMEWORK MÔ HÌNH CODE FIRST
7.2.3 DBContext context trong Entity Framework
Student.cs và Faculty.cs
(Create, Read, Update, và Delete) mà
SaveChanges() using (var context = new StudentModel())
{ var f = new Faculty() { FacultyID = 100, FacultyName= "CNTT" }; context.Faculties.Add(f); //Add vào DbSet context.SaveChanges();
} using (var context = new StudentModel())
{ var s = new Student() { StudentID = "1799062090", FullNameSang", AverageScore = 7.6, FacultyID= 100}; context.Students.Add(s); //Add vào DbSet context.SaveChanges();
1799 using (var context = new StudentModel())
{ var std = context.Students.First(p => p.StudentID ="1799062090"); std.FullName = ; std.AverageScore = 8.6; context.SaveChanges();
1799062090 using (var context = new StudentModel())
{ var std = context.Students.First(p => p.StudentID ="1799062090"); context.Students.Remove(std); //Remove trong DBSet context.SaveChanges();
// #2: method syntax (lambda expression s=>s.AverageScore>=5)
List studentList = context.Students.Where(s => s.AverageScore
>= 5).ToList(); foreach (Student s in studentList)
Khoa = {3}", s.StudentID, s.FullName, s.AverageScore, s.Faculty.FacultyName);
150 using (var ctx = new StudentModel())
{ var studentList = ctx.Students.SqlQuery("SELECT * from Student WHERE AverageScore>=5").ToList();
ObjectQuery thay vì IQueryable. string sqlString = "SELECT VALUE st FROM SchoolDBEntities.Students " + "AS st WHERE st.AverageScore >= 5"; var objctx = (ctx as IObjectContextAdapter).ObjectContext;
ObjectQuery student = objctx.CreateQuery(sqlString); var studentList = student.ToList();
NHÂN VIÊN: Mã nhân viên
PHÒNG BAN Mã phòng , tên
M Ô HÌNH 3
Mô hình 3- và mô hình -
M Ô HÌNH 3 (3- LAYERS )
- Service Agents: n lí thành viên Presentation,
Library và Add Reference vào project GUI
8.3 MÔ HÌNH 3 L P VÀ ENTITY FRAMEWORK
- BUS: viên, khoa, chuyên ngành
3-layer và EF code first:
Câu 1: Mô hình 3-tier là gì ? Cho
Câu 5: các mô hình MVC (Model-View-