Gopal
Gopal

Reputation: 11982

How to avoid the duplicate values

When I add the value from database, the listbox should avoid the duplicate value.

For Example

List1 box

 Value

100
200'
300

From the table, when i add the same value 001, the listbox should avoid the value. When I try to add 400, the listbox should allow to add.

Upvotes: 0

Views: 750

Answers (4)

rskar
rskar

Reputation: 4657

The VB6 ListBox control does not have a method to determine if it already contains a given value. You will have to use the List() and ListCount properties of the ListBox to do a search. If the ListBox has Sorted=True, you can use a binary search pattern; otherwise it will have to be a sequential search.

I am assuming that you are populating the items via AddItem, and not data bindings (DataSource, DataField etc.). If you are using data bindings, then you will need to work on the SQL, and perhaps use DISTINCT, as jworrin has recommended.

Upvotes: 1

JMax
JMax

Reputation: 26591

When you create your listbox, you should use a dictionary to store all these values.

Then, you can check if the value exists:

If Not dict.Exists(key) Then 
    dict.Add key, value
    listitem.Add key
End If 

See this thread for more information: Does VBA have Dictionary Structure?

Upvotes: 3

Deanna
Deanna

Reputation: 24263

To avoid adding duplicates, you will need to check every entry already in the list. You can get around this in domain specific ways but it depends on what else the code is doing.

But... To reiterate what jworrin said, You should restructure your database query to only get the data you want to display.

Upvotes: 0

jworrin
jworrin

Reputation: 835

Not sure if I understand your question, but I would recommend limiting the values when they are coming back from the database. With out any idea of what your database looks like, I would recommend looking up DISTINCT and using it in your query that returns the list for your listbox

Upvotes: 1

Related Questions