Các bài tập Microsoft .NET 171
Private Sub ListBox1_SelectedIndexChanged( ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles ListBox1.SelectedIndexChanged
Try
If ListBox1.SelectedValue <> "" Then
MessageBox.Show(ListBox1.SelectedValue & " of " & ListBox1.SelectedItem.ToString,
"Selected value")
End If
Catch ex As Exception
' Do nothing, ignore this error
End Try
End Sub
Như thế ta đã implemented (thi hành) cho .NET ListBox một chức năng
tương đương với ItemData của ListBox trong VB6.
.NET ListBox không hổ trợ Style Checkbox, nhưng ta có thể dùng
CheckedListBox.
ComboBox
Vì ComboBox thừa kế từ ListBox nên tất cả những gì ta biết về ListBox
đều áp dụng cho ComboBox. Đặc biệt bây giờ ComboBox có property
MaxDropDownItems cho ta quyết định hiển thị bao nhiêu items khi
danh sách được mở ra.
Kèm theo đây là một chương trình biểu diễn ComboBox trong đó ta dùng
Property ValueMember của ComboBox để trả về một trị số đại diện
Item. Data trong ComboBox1 được loaded từ một Access2000 database
table bằng code sau đây:
Private Sub frmCombo_Load( ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles MyBase.Load
Dim ds As New DataSet () ' Instantiate a Dataset
' Instantiate an OleDbDataAdapter for Access2000 database Authors.mdb and return table Authors
Dim myData As New OleDbDataAdapter("Select * from Authors",
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= \Authors.mdb")
Label1.Text = ComboBox1.SelectedValue
Catch
End Try
Các bài tập Microsoft .NET 173
End Sub
Ở đây có hai cách để ta select một ComboBox item bằng coding. Cách
thứ nhất là cho biết AuthorId (ValueMember), user clicks button Select
by AuthorId để thấy kết quả:
Private Sub BtnSelectbyAuthorId_Click_1( ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles BtnSelectbyAuthorId.Click
'Use Try to ignore error if operation fails
Try
' Select the ComboBox Item whose valueMember equal txtAuthorId.Text
ComboBox1.SelectedValue = txtAuthorId.Text
Catch
End Try
End Sub
và cách thứ hai là cho biết FullName (DisplayMember), user clicks
button Select by Name để thấy kết quả:
Private Sub BtnSelectByName_Click( ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles BtnSelectByName.Click
'Use Try to ignore error if operation fails
Try
' Select the ComboBox Item whose DisplayMember equal txtFullName.Text
' FindString returns the index of the found item
ComboBox1.SelectedIndex = ComboBox1.FindString(txtFullName.Text)
Catch
End Try
End Sub
Khi chạy chương trình, bạn sẽ thấy hình như CÁCdưới đây. Trong hình