-
Feb 7th, 2015, 09:25 PM
#1
Thread Starter
Hyperactive Member
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?
-
Feb 7th, 2015, 09:59 PM
#2
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.
-
Feb 7th, 2015, 10:17 PM
#3
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:
Private Sub ComboBox1_Validating(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles ComboBox1.Validating Dim index = ComboBox1.FindStringExact(ComboBox1.Text) e.Cancel = (index = -1) 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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|