Results 1 to 3 of 3

Thread: Combo box data

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Apr 2012
    Posts
    391

    Combo box data

    So I've got a DataTable with rows of information, i'm using this to create a AutoComplete Source and list items.

    I don't want the dropdown style where you can't type things in.

    I do however want to prevent users typing something which isn't an option. How can I do this?

  2. #2
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    105,477

    Re: Combo box data

    You can't easily prevent them from typing something that isn't in the list. What you can do is prevent them leaving the control until they do enter an item from the list. I'll throw together an example of that that demonstrates the use of the Validating and Validated events.

  3. #3
    .NUT jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    105,477

    Re: Combo box data

    Actually, when I created the example I realised that you don't even need to handle the Validated event. Just the Validating event is enough.
    vb.net Code:
    1. Private Sub ComboBox1_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles ComboBox1.Validating
    2.     Dim index = ComboBox1.FindStringExact(ComboBox1.Text)
    3.  
    4.     e.Cancel = (index = -1)
    5. End Sub
    The Validating event is raised when the user tries to leave the control, or when you call Validate or ValidateChildren in code. My example code takes the text currently in the ComboBox and looks for an item in the drop-down list with the same text. If a match is found then that will return the index of that matching item, otherwise it will return -1. If -1 is returned then e.Cancel is set to False and that means that the control will not lose focus. The user will have to enter a value that does match an item before they can shift focus to another control. You might add a MessageBox.Show in there when validation fails so that they know what they've done wrong.

    When the Validating event handler completes, if e.Cancel is True then the Validated event is raised. There you can perform post-validation tasks before focus actually shifts. I was going to use the handler for that event to actually select the matching item in the drop-down list but I found that that actually happens automatically, so there was no need for any code to do it.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width