In a recent project enhancing some functionality to an existing .Net v2.x web application I had the need to remove duplicate entries in a DropDownList. As with most challenges I haven’ had the pleasure of resolving before, I took it to Google. Of course I got a plethora of suggestions to eliminate the duplicates in the data before binding or query the database with DISTINCT.
But I was dealing with an existing application, that stored the query results in an ArrayList of data objects. Also the results included location data, such as City, State, Market and Region, that I was providing drop down filters on, so eliminating the duplicates in the query was out of the question and I did not want to make another query to the database.
Eventually I found a solution in this post and modified it to be more generic as seen here:
- Public Shared Function DDL_RemoveDuplicateItems(ByVal ddl As DropDownList) As DropDownList
- For i As Integer = 0 To ddl.Items.Count – 1
- ddl.SelectedIndex = i
- Dim str As String = ddl.SelectedItem.ToString()
- For counter As Integer = i + 1 To ddl.Items.Count – 1
- ddl.SelectedIndex = counter
- Dim compareStr As String = ddl.SelectedItem.ToString()
- If str = compareStr Then
- ddl.Items.RemoveAt(counter)
- counter = counter – 1
- End If
- Next
- Next
- Return ddl
- End Function
But I quickly found that if all rows were from the same State or Region, all entries were duplicates and this function would delete all entries, but I wanted to leave at least one. Also, it did not properly handle deleting the last entry in the DDL, so I modified it and it works quite well.
- Public Shared Function DDL_RemoveDuplicateItems(ByVal ddl As DropDownList) As DropDownList
- For i As Integer = 0 To ddl.Items.Count – 1
- ddl.SelectedIndex = i
- Dim str As String = ddl.SelectedItem.ToString()
- For counter As Integer = i + 1 To ddl.Items.Count – 1
- ddl.SelectedIndex = counter
- Dim compareStr As String = ddl.SelectedItem.ToString()
- If str = compareStr Then
- Try
- If ddl.Items.Count = 1 Then
- ‘ There is only ONE item in the list, it is not duplicate, do not remove it
- Return ddl
- ElseIf counter = ddl.Items.Count – 1 Then
- ‘ Removing last item in the list.
- ddl.Items.RemoveAt(counter)
- Exit For
- Else
- ‘ Remove item and keep going
- ddl.Items.RemoveAt(counter)
- counter = counter – 1
- End If
- Catch ex As Exception
- Dim err As String = ex.Message
- End Try
- End If
- Next
- Next
- Return ddl
- End Function
I realize that this functionality is not needed often but… I would think by v2.x and newer releases a RemoveDuplicates function would be provided.