3

我决定向我的组合框添加一些验证,我想要实现的是确保用户只能输入组合框中的字段,但我现在遇到的问题是,如果用户点击组合框和不输入任何内容并尝试离开组合框,出现消息框。

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

如前所述,编码确实有效,但我试图确保如果用户未在组合框中输入任何内容,则不会出现消息框。

4

2 回答 2

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
于 2012-06-15T22:56:32.487 回答
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
于 2013-04-07T01:32:39.363 回答