List cho phép ta tạo ra một danh sách các phần tử để lựa chọn. Nếu như số lượng các phần tử lớn hơn số lượng mà danh sách có thể hiển thị trên màn hình (do ta design danh sách có kích thước cao hay ngắn) thì một thanh cuộn sẽ tự động thêm vào trong danh sách để cho ta có thể list qua hết các phần tử. Danh sách List trình bày tất cả (hay một phần các phần tử tuỳ theo số lượng phần tử và độ dài trong giao diện của List), ta có thể chọn ra một hay nhiều phần tử cùng một lúuc từ danh sách để xử lý.
Từ phần này, các thuộc tính của các control mà nó giống với các thuộc tính ở trên thì tôi không trình bày ra ở đây nữa.
Tên Thuộc tính |
Giá Trị |
Diễn giải |
MultiColumn | True False (mặc định) | Cho phép hiển thị các item thành các cột thay vì 1 cột như mặc định của nó |
SelectionMode | None | Không có item nào được chọn. Dách sách chỉ để hiển thị xem mà thôi |
One | Chỉ có 1 item được phép chọn. | |
MultiSimple | Có nhiều item được phép chọn cùng một lúc. | |
MultiExtended | Giống như MultiSimple nhưng ta có thể dùng phím như SHIFT, các phím mũi tên để chọn. | |
Sorted | True False | Sắp xếp danh sách theo thứ tự aphabet |
Items | Collection… | Một hộp hội thoại cho phép bạn nhập vào danh sách các item. |
Khi bạn chọn Items Collection…, một hộp hội thoại String Collection Editor hiển thị ra cho phép bạn nhập vào các items: Đối với Listbox, bạn có thể sử dụng dữ liệu lấy tự database lên thay cho các dữ liệu bạn nhập vào để làm danh sách. Phần database ta sẽ học ở phần sau.
Sự kiện quan trọng và hay sử dụng nhất của Listbox là SelectedIndexChange. Sự kiện này được phát sinh khi bạn click chuột vào 1 item khác hay bạn dùng phím mũi tên để di chuyển giữa các item.
Tạo một project có tên ListBoxDemo cho phép chọn lựa sinh viên vào một lớp từ một danh sách các sinh viên như hình dưới đây: Các thuộc tính:
Đối Tượng |
Thuộc Tính |
Giá Trị |
Form |
Name Text | frmListDemo Listbox Demo Application |
ListBox |
Name Items | lstNguon Danh sách các sinh viên (tự nhập) |
ListBox |
Name Items | lstDich Bỏ trống |
Button |
Name Text | btnAdd > |
Button |
Name Text | btnAddAll >> |
Button |
Name Text | btnRemove < |
Button |
Name Text | btnRemoveAll << |
Label |
Name Text | default Danh sách SV: |
Label |
Name Text | default Danh sách lớp: |
Dưới đây là source code:
Dưới đây là source code:
private void btnAdd_Click(object sender, System.EventArgs e)
{
try
{
lstDich.Items.Add(lstNguon.SelectedItem);
lstNguon.Items.Remove(lstNguon.SelectedItem);
}
catch(ArgumentNullException nex)
{
MessageBox.Show(“Bạn chưa chọn sinh viên nào!!!”);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnAddAll_Click(object sender, System.EventArgs e)
{
foreach(string item in lstNguon.Items)
lstDich.Items.Add(item);
lstNguon.Items.Clear();
}
private void btnRemove_Click(object sender, System.EventArgs e)
{
try
{
lstNguon.Items.Add(lstDich.SelectedItem);
lstDich.Items.Remove(lstDich.SelectedItem);
}
catch(ArgumentNullException nex)
{
MessageBox.Show(“Bạn chưa chọn sinh viên nào!!!”);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void btnRemoveAll_Click(object sender, System.EventArgs e)
{
foreach(string item in lstDich.Items)
lstNguon.Items.Add(item);
lstDich.Items.Clear();
}
Giải thích: Ở phần source code bên trên, bạn thấy có 2 cái mới: đó là phần bắt lỗi: try{} catch{} và vòng lặp foreach. Hai phần này sẽ được giải thích kỹ ở phần lập trình hướng đối tượng mà ta sẽ học sau. Ở đây, tôi chỉ giải thích sơ về 2 câu lệnh cú pháp này. – try{} catch{} là câu lệnh dùng để bắt lỗi. Các source code mà ta cần bắt lỗi sẽ để ở trong try{} và nếu như có xảy ra lỗi thì tự động dừng lại và nhảy ra khỏi khối try{} và đi vào trong khối catch{}. Ở đây ta sẽ xử lý các lỗi dựa vào biểu thức expression. Cách bắt lỗi ở phần catch{} có thể có nhiều khối (như ví dụ trên gồm 2 khối bắt lỗi): catch(ArgumentNullException nex) { MessageBox.Show(“Bạn chưa chọn sinh viên nào!!!”); } catch(Exception ex) { MessageBox.Show(ex.Message); } Exception là phần bắt tất cả các lỗi xảy ra nên bao giờ cũng để ở sau cùng. Cú pháp sẽ là:
try khối lệnh try
catch (exception để bắt lỗi 1) khối lệnh catch 1
catch (exception để bắt lỗi 2) ckhối lệnh catch 2
.....
với: try-block Chứa code mà ta xác định có thể xảy ra lỗi. exception-1, exception-2 Khai báo đối tượng bắt lỗi expression. catch-1, catch-2 Gồm các câu lệnh để xử lý lỗi. – Câu lệnh lặp foreach dùng để lặp qua tất cả các phần tử trong 1 mảng hay trong 1 tập (collection). foreach(string item in lstDich.Items) lstNguon.Items.Add(item); Như ở ví dụ trên, collection của ta là tập các items của listbox. Cú pháp sẽ là: foreach (ItemType item in myCollection) Items là một collection nên khi ta thêm hay remove các item đều phải sử dụng đến collection items. – Thêm vào: có 2 cách: Add và Insert. Add dùng để thêm 1 item vào nối đuôi danh sách hiện có, còn Insert là bạn sẽ chèn vào 1 vị trí nào đó trong danh sách. Vì vậy, Insert sẽ có 2 tham số truyền vào. Listbox.Items.Add(“phúc”) : thêm “phúc“ vào danh sách (nối đuôi). Listbox.Items.Insert(1, “phúc”) : thêm “phúc” vào danh sách ở vị trí thứ 2 (vì danh sách được đánh số từ 0). – Xoá bỏ: cũng có 2 cách: Remove và RemoveAt. Remove sẽ có đối số truyền vào là 1 chuỗi chỉ tên item còn RemoveAt sẽ có đối số truyền vào là số nguyên int chỉ index của danh sách. Listbox.Items.Remve(“phuc”); Listbox.Items.RemoveAt(1); Để nhận biết 1 item nào được chọn thì ta sử dụng 2 cách là SelectedItems và SelectedIndex. SelectedItem trả về tên (kiểu string) của item mà ta chọn còn SelectedIndex thì trả về 1 số (kiều int) của item mà ta chọn. Trong ví dụ trên, đầu tiên bạn không chọn thuộc tính Sorted = false (mặc nhiên) cho 2 listbox, và bạn sẽ thấy mỗi lần thêm thì nó sẽ tự động thêm vào cuối danh sách. Sau đó, bạn hãy chọn Sorted = true và hãy nhận xét những thay đổi. Lưu ý: Trong ví dụ trên, khi biên dịch, trình biên dịch sẽ warning một số lỗi và có đường kẻ xanh loăn quăn ở dưới câu lệch catch nhưng ta không lo vì nó chỉ cảnh báo là biến nex có khai báo nhưng không được sử dụng. CÁC BÀI TẬP LÀM THÊM :
Hình 1. Ứng dụng Quản lý khách hàng
Hình 2. GUI form Thêm sách
public class customer
{
private string lastname;
public string Lastname
{
get { return lastname; }
set { lastname = value; }
}
private string firstname;
public string Firstname
{
get { return firstname; }
set { firstname = value; }
}
private string email;
public string Email
{
get { return email; }
set { email = value; }
}
public customer()
{
}
public customer(string lastname, string firstname, string email)
{
this.lastname = lastname;
this.firstname = firstname;
this.email = email;
}
public virtual string showCustomer()
{
return lastname + ” ” + firstname + “, ” + email;
}
}
Hình 3. Giao diện form frmAddCustomer
public partial class frmAddNewCustomer : Form
{
public frmAddNewCustomer()
{
InitializeComponent();
}
private void frmAddNewCustomer_Load(object sender, EventArgs e)
{
}
public customer a = null;
private void button1_Click(object sender, EventArgs e)
{
a = new customer();
a.Lastname = textBox1.Text;
a.Firstname = textBox2.Text;
a.Email = textBox3.Text;
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
public customer getcustomer()
{
this.ShowDialog();
return a;
}
}
Hình 4. GUI form frmCustomers
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
List<customer> ds = new List<customer>();
private void xuat_danhsach()
{
listBox1.Items.Clear();
for (int i = 0; i < ds.Count; i++)
{
listBox1.Items.Add(ds[i].showCustomer());
}
}
private void button1_Click(object sender, EventArgs e)
{
frmAddNewCustomer frm = new frmAddNewCustomer();
customer a = frm.getcustomer();
if (a != null)
{
ds.Add(a);
}
xuat_danhsach();
}
private void button2_Click(object sender, EventArgs e)
{
int i = listBox1.SelectedIndex; //Lấy vị trí mà người dùng chọn
if (i != -1) //Nếu người dùng có chọn một phần tử trên listbox
{
customer a = (customer)ds[i];
string message = “Có phải bạn muốn xóa ”
+ a.Firstname + ” ” + a.Lastname + “không?”;
DialogResult kq = MessageBox.Show(message, “Xác nhận xóa”,
MessageBoxButtons.YesNo);
if (kq == DialogResult.Yes)
{
ds.Remove(a);
xuat_danhsach();//Hiển thị lại
}
}
}
private void button3_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
Hướng dẫn :
code lớp customer
2 |
5 |
public class customer
{
private string lastname;
public string Lastname
{
get { return lastname; }
set { lastname = value; }
}
private string firstname;
public string Firstname
{
get { return firstname; }
set { firstname = value; }
}
private string email;
public string Email
{
get { return email; }
set { email = value; }
}
public customer()
{
}
public customer(string lastname, string firstname, string email)
{
this.lastname = lastname;
this.firstname = firstname;
this.email = email;
}
public virtual string showCustomer()
{
return lastname + ” ” + firstname + “, ” + email;
}
}
2. code lớp khách hang sỉ
public class WholesaleCustomer : customer
{
private string company;
public string Company
{
get { return company; }
set { company = value; }
}
public override string showCustomer()
{
return Lastname + ” ” + Firstname + “, ” + Email+ “, ” +Company;
}
}
public class RetailCustomer : customer
{
private string mobilephone;
public string Mobilephone
{
get { return mobilephone; }
set { mobilephone = value; }
}
public override string showCustomer()
{
return Lastname + ” ” + Firstname + “, ” + Email + “, ” + Mobilephone;
}
}
public partial class frmWholesaleCustomer : Form
{
public frmWholesaleCustomer()
{
InitializeComponent();
}
public WholesaleCustomer a = null;
private void button1_Click(object sender, EventArgs e)
{
a = new WholesaleCustomer();
a.Lastname = textBox1.Text;
a.Firstname = textBox2.Text;
a.Email = textBox3.Text;
a.Company = textBox4.Text;
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
public customer getcustomer()
{
this.ShowDialog();
return a;
}
}
public partial class frmRetailCustomer : Form
{
public frmRetailCustomer()
{
InitializeComponent();
}
public RetailCustomer a = null;
private void button1_Click(object sender, EventArgs e)
{
a = new RetailCustomer();
a.Lastname = textBox1.Text;
a.Firstname = textBox2.Text;
a.Email = textBox3.Text;
a.Mobilephone = textBox4.Text;
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
public customer getcustomer()
{
this.ShowDialog();
return a;
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
List<customer> ds = new List<customer>();
private void xuat_danhsach()
{
listBox1.Items.Clear();
for (int i = 0; i < ds.Count; i++)
{
listBox1.Items.Add(ds[i].showCustomer());
}
}
private void button1_Click(object sender, EventArgs e)
{
frmAddNewCustomer frm = new frmAddNewCustomer();
customer a = frm.getcustomer();
if (a != null)
{
ds.Add(a);
}
xuat_danhsach();
}
private void button2_Click(object sender, EventArgs e)
{
int i = listBox1.SelectedIndex; //Lấy vị trí mà người dùng chọn
if (i != -1) //Nếu người dùng có chọn một phần tử trên listbox
{
customer a = (customer)ds[i];
string message = “Có phải bạn muốn xóa ”
+ a.Firstname + ” ” + a.Lastname + “không?”;
DialogResult kq = MessageBox.Show(message, “Xác nhận xóa”,
MessageBoxButtons.YesNo);
if (kq == DialogResult.Yes)
{
ds.Remove(a);
xuat_danhsach();//Hiển thị lại
}
}
}
private void button3_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void button4_Click(object sender, EventArgs e)
{
frmWholesaleCustomer frm = new frmWholesaleCustomer();
customer a = frm.getcustomer();
if (a != null)
{
ds.Add(a);
}
xuat_danhsach();
}
private void button5_Click(object sender, EventArgs e)
{
frmRetailCustomer frm = new frmRetailCustomer();
customer a = frm.getcustomer();
if (a != null)
{
ds.Add(a);
}
xuat_danhsach();
}
}
Tạp chí tri thức và sáng tạo