Jump to content

Check out our Community Blogs

Register and join over 40,000 other developers!

Recent Status Updates

View All Updates

- - - - -

Validating a combo box


  • Please log in to reply
1 reply to this topic

#1 standard


    CC Lurker

  • Just Joined
  • Pip
  • 4 posts

Posted 26 April 2010 - 05:01 PM

Ok so I have a combobox linked to a table in a database.
At the moment it looks up all the records stored under the field name 'Firstname' and stores it in the combobox.

So the combobox has items such as (james, john, bill)

However as the items depend on what is stored in the database it can change each time the program is run.

I want to create a validation so that the user has to enter in one of the options in the combo box. Ideally i could do something like (if entry <> allitems) then (show error)

However allitems is clearly not possible!

Any help would be appreciated! Thanks in advance
  • 0

#2 Firebird_38


    CC Addict

  • Advanced Member
  • PipPipPipPipPip
  • 117 posts

Posted 03 May 2010 - 12:31 PM

first off, you can make a combobox so that you can't type in it, so they can only select something in the actual list. I forget how, but it's easy to figure out. The property is called something like "dropdownstyle", but I forget. Select "dropdownfixed" I think, but I forget. Play around with it until it works.

If, for some unknown reason, you want users to be able to type so you can then smack them an error in the face to be sadistic, you can check using this code:

function CheckCombo(c:TComboBox):Boolean; //returns fals if it's not ok
var n:integer;
 result:=true; //assume we'll find it
 for n:=0 to c.Items.Count-1 do
   if c.Items[n]=c.Text then exit; //we found it, so we're done, get the ** out
 //We're still here, so that means we didn't find it!
 result:=false; //out assumption above was wrong, so un-assume :)

You can use it:
procedure form1.button1click(sender:TObject);
 if not CheckCombo(ComboBox1) then
  ShowMessage('You''re a moron! You can''t enter '+ComboBox1.Text+' because it''s not in the list!');

For production code, you may want to edit the message to be more user-friendly as opposed to user-rude :)

Please note:
  • Showing a message doesn't do anything. The text is still there and this needs to be dealt with.
  • This is not complete. It needs some help.
  • Again, you don't need to ceck if you make it impossible to select anything except what's in the list.
  • If the user doesn't use the same capitalization as in the list, they're screwed. You can commpare instead using uppercase() (if UpperCase(c.Items[n])=UpperCase(c.Text) ...)
  • It's assumed the user is going to click a button here... That's stupid. They don't want to be called a moron, so they're not going to click. So find a better way to validate. I don't know your program, so I can't help there.
Good luck
  • 0

Posted Image

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download