Thiết kế DataGrid

Một phần của tài liệu hướng dẫn sử dụng visual basic (Trang 147 - 150)

I. Các điều khiển hiển thị dữ liệu

I.6.Thiết kế DataGrid

Khi DataGrid liên kết với nguồn dữ liệu, nếu chúng ta khơng tạo DataGridTableStyle qui định cách hiển thị dữ liệu, lưới sẽ hiển thị dữ liệu theo định dạng mặc định của lưới. Để lưới hiển thị dữ liệu theo ý muốn, chúng ta phải tạo DataGridTableStyle và các thành phần của nĩ.

I.6.1. Tạo DataGridTableStyle khi thiết kế (Design time)

Chúng ta tạo DataGridTableStyle và các DataGridColumnStyle theo các bước sau :

ƒ Chọn thuộc tính TableStyle trên Properties và nhấn nút […]

ƒ Trên cửa sổ kế tiếp nhấn nút [Add] để tạo một DataGridTableStyle mới, khai báo các thuộc tính cần thiết như MappingName, ReadOnly,… và nhấn nút […] ở mục

GridColumnStyles để tạo các DataGridColumnStyle.

Tạo DataGridTableStyle mới

ƒ Trên cửa sổ kế tiếp nhấn nút [d] bên phải nút [Add] để lựa chọn loại DataGridColumnStyle muốn tạo, mặc định là DataGridTextBoxColumn :

Chọn loại DataGridColumnStyle

ƒ Nhấn nút [Add] để tạo một DataGridColumnStyle đã chọn và khai báo các thuộc tính cần thiết : Alignment, HeaderText, Width, Format, MappingName, ReadOnly, NullText…Tiếp tục các cột khác

Tạo DataGridColumnStyle mới và khai báo

I.6.2. Tạo DataGridTableStyle lúc thực thi (Runtime)

Sử dụng lệnh tạo mới một DataGridTableStyle, kế tiếp tạo các DataGridColumnStyle và thêm vào GridColumnStyles của DataGridTableStyle, sau cùng thêm DataGridTableStyle vừa tạo vào tập hợp TableStyles của lưới.

Đoạn lệnh sau đây minh họa tạo DataGridTableStyle hiển thị dữ liệu bang_phong trên lưới LUOI_PHONG.

Ví dụ:

Dim kieu_hien_thi_bang_phong As New DataGridTableStyle() With kieu_hien_thi_bang_phong

.MappingName = bang_phong.TableName

Dim cot_ma_phong As New DataGridTextBoxColumn()

cot_ma_phong.MappingName = bang_phong.Columns(0).ColumnName cot_ma_phong.HeaderText = “Mã PB”

cot_ma_phong.Width = 40

.GridColumnStyles.Add(cot_ma_phong)

Dim cot_ten_phong As New DataGridTextBoxColumn()

cot_ten_phong.MappingName = bang_phong.Columns(1).ColumnName cot_ten_phong.HeaderText = “Tên phịng ban”

cot_ten_phong.Width = 150

.GridColumnStyles.Add(cot_ten_phong) End With

Kinh nghiệm giảng dạy:

Luơn luơn tạo các DataGridColumnStyle và thêm chúng vào GridColumnStyles của DataGridTableStyle trước khi thêm DataGridTableStyle này vào TableStyles của lưới. Khi thêm một DataGridTableStyle rỗng (chưa cĩ các DataGridColumnStyle) vào TableStyles, các DataGridColumnStyle sẽ được phát sinh tự động, vì thế khi chúng ta thêm DataGridColumnStyle vào sẽ phát sinh lỗi do cĩ các DataGridColumnStyle cĩ MappingName trùng nhau

Một phần của tài liệu hướng dẫn sử dụng visual basic (Trang 147 - 150)