Avoid Duplicate in Combobox
Hi All,
I have a combo box control in my application. I have to add the items from the database. I added it from database. But it adding duplicate data. Like by running the combo box second time it adding the same data once again. So i need to check the combo box that the data item is new to the combo box or a old one. If its a old one it should be avoid or else it want to be added to the combo box.
I used SQL server2000 and SQL query to load the data into the combo box. so let me have a idea on it.
Thanks all.
Re: Avoid Duplicate in Combobox
The short answer to your question is to call Contains on the control's Items collection to tell you whether a value is already in the list.
That may not be the best solution though. How exactly are you populating the ComboBox in the first place? How are you getting the new data and how does it come about that it contains duplicates? It would likely be better if you could avoid retrieving duplicates in the first place. It would also be likely better to just bind your data.
Re: Avoid Duplicate in Combobox
There are two ways:
1. Clear all the items from Combo box and add all the items again.
vb.net Code:
Private Sub Button2_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs _
) Handles Button2.Click
ComboBox1.Items.Clear()
ComboBox1.Items.Add("One")
ComboBox1.Items.Add("Two")
ComboBox1.Items.Add("Three")
ComboBox1.Items.Add("Four")
End Sub
2. Before adding any item to the combo box, check for it's existence in the combo box item list collection. If not found then add it else ignore.
vb.net Code:
Private Sub Button1_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs _
) Handles Button1.Click
If ComboBox1.Items.IndexOf(TextBox1.Text) = -1 Then
ComboBox1.Items.Add(TextBox1.Text)
End If
End Su