Click here to Skip to main content
15,880,725 members
Please Sign up or sign in to vote.
3.00/5 (4 votes)
See more:
Hi friends

I have written a function that validates comboboxes in my project. The function works fine with comboboxes that are populated at design time. But it will not work when I used it with comboboxes that via database at runtime

I have show the function and the validate event handler for comboboxes

The function:

VB
 Public Function validateCombo(txt As ComboBox) As Boolean
 If Not txt.Items.Contains(txt.Text.ToString) Then
    Return False
 Else
    Return True
 End If
End Function


Combo event handler:

VB
Private Sub cboFund_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles cboFund.Validating
       If Not bnformclosing Then
           If cboFund.Text <> String.Empty Then

               If validateCombo(cboFund) Then
                   e.Cancel = False
               Else
                   MessageBox.Show("The item: " & cboFund.Text & " is not a valid fund", "Invalid fund", MessageBoxButtons.OK, MessageBoxIcon.Information)
                   e.Cancel = True
               End If
           End If
       End If
   End Sub
Posted
Updated 17-Dec-12 7:08am
v2
Comments
Kschuler 17-Dec-12 13:43pm    
What error message do you get? What do you mean by "it will not work"?
noblepaulaziz 17-Dec-12 15:26pm    
it does not pass validation test. Which means that the item is not in the list whereas the item is in the list
Kschuler 17-Dec-12 16:24pm    
Perhaps instead of checking the Text of the combobox, you should check the SelectedValue?
noblepaulaziz 17-Dec-12 16:57pm    
Thanks for the reply. I will try your suggestion and let you know the feedback

Thanks once again
Sergey Alexandrovich Kryukov 17-Dec-12 14:28pm    
Bad idea: you are showing modal MessageBox each time you are validating. Use something non-modal, just output some validation results in some control on the same form.
—SA

ComboBox.Items.Contains() method search through the object collection which are bound to the ComboBox. When you add string values, this method can be called by providing a string value as parameter. But when you bind a DataTable, the object type will be DaraRow. You have to provide a DataRow object to ComboBox.Items.Contains() method in this scenario.

Or use ComboBox.FindString() or ComboBox.FindStringExact(). That is the easiest way
 
Share this answer
 
You Can use the Combobox dropdown list property
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900