我决定在我的组合框中添加一些验证,我想要实现的是确保用户只能输入组合框中的字段,但我现在遇到的问题是如果用户点击组合框并没有输入任何东西,并试图让消息框出现在组合框中。
Private Sub Combobox1_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles Combobox1.Validating
If Combobox1.Items.Contains(Combobox1.Text) = False Then
e.Cancel = True
End If
End Sub
Private Sub Combobox1_Leave(sender As Object, e As System.EventArgs) Handles Combobox1.Leave
If Combobox1.Items.Contains(Combobox1.Text) = False Then
Combobox1.Select()
MessageBox.Show("select item from combobox")
End If
End Sub
如前所述,编码确实有效,但我试图确保如果用户没有在组合框中输入任何内容,则不会出现消息框。
答案 0 :(得分:4)
根据您的评论,我认为您需要做的就是添加一个空字符串检查:
Private Sub ComboBox1_Validating(ByVal sender As Object, ByVal e As CancelEventArgs) Handles ComboBox1.Validating
If ComboBox1.Items.Contains(ComboBox1.Text) = False Then
e.Cancel = (ComboBox1.Text <> String.Empty)
End If
End Sub
Private Sub ComboBox1_Leave(ByVal sender As Object, ByVal e As EventArgs) Handles ComboBox1.Leave
If Not ComboBox1.Items.Contains(ComboBox1.Text) Then
If ComboBox1.Text <> String.Empty Then
ComboBox1.Select()
MessageBox.Show("select item from combobox")
End If
End If
End Sub
答案 1 :(得分:1)
使用此代码:
Private Sub Combobox1_Leave(sender As Object, e As System.EventArgs) Handles Combobox1.Leave
If ComboBox2.SelectedIndex = -1 Then
MessageBox.Show("select item from combobox")
End If
End Sub