Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Dưới đây là phần mã cho lớp AutoCompleteComboBox: using System; using System.Windows.Forms; public class AutoCompleteComboBox | Dưới đây là phần mã cho lớp AutoCompleteComboBox using System using System.Windows.Forms public class AutoCompleteComboBox ComboBox Biến cờ dùng khi một phím đặc biệt được nhấn trong trường hợp này thao tác thay thế text sẽ bị bỏ qua . private bool controlKey false Xác định xem phím đặc biệt có được nhấn hay không. protected override void OnKeyPress System.Windows.Forms.KeyPressEventArgs e base.OnKeyPress e if e.KeyChar int Keys.Escape Xóa text. this.Selectedlndex -1 this.Text controlKey true else if Char.IsControl e.KeyChar controlKey true else controlKey false Thực hiện thay thế text. protected override void OnTextChanged System.EventArgs e base.OnTextChanged e if this.Text controlKey Tìm kiếm item trùng khớp. string matchText this.Text int match this.FindString matchText Nếu tìm thấy thì chèn nó vào. if match -1 this.SelectedIndex match Chọn bôi đen phần text vừa thêm vào để nó có thể được thay thế nếu người dùng kiếp tục gõ. this.SelectionStart matchText.Length this.SelectionLength this.Text.Length - this.SelectionStart Để thử nghiệm AutoCompleteComboBox bạn có thể tạo một client đơn giản thêm ComboBox vào form và thêm một số từ word vào ComboBox. Trong ví dụ này các từ được lấy từ một file text và ComboBox được thêm vào form bằng mã lệnh. Bạn cũng có thể biên dịch lớp AutoCompleteComboBox thành một Class Library Assembly độc lập rồi thêm nó vào hộp công cụ thế là bạn có thể thêm nó vào form lúc thiết kế. using System using System.Windows.Forms using System.Drawing using System.IO public class AutoCompleteComboBoxTest System.Windows.Forms.Form Bỏ qua phần mã designer. private void AutoCompleteComboBox_Load object sender System.EventArgs e Thêm ComboBox vào form. AutoCompleteComboBox combo new AutoCompleteComboBox combo.Location new Point 10 10 this.Controls.Add combo Thêm một số từ từ một file text vào ComboBox. FileStream fs new FileStream words.txt FileMode.Open using StreamReader r new StreamReader fs while r.Peek -1 string word r.ReadLine combo.Items.Add .