RobLog

Web Design in the World of .NET (C# and VB.NET, XML, and Javascript). I learned how to program from TheDailyWTF.com!
posts - 140, comments - 129, trackbacks - 5

My Links

News

Main Site Cert Corner Goals About Me

Article Categories

Archives

Post Categories

Image Galleries

.NET

Personal

WOW


Removing Duplicates from Lists After DataBind()

If you pull information from a database and you want to use the same data that you are going to display (i.e. not using distincts) in your server controls (like a drop down list), then you may want to only show the distinct items from that information particular to your control.

 

Example: Say I pulled forty items out of a database and I wanted the user to be able to select a year and filter my results based on that year.  I want the drop down list to only contain years that the database has in it.  When I fill the control, I get more than one instance of every year.  I only want to see one instance.  So I need to go in and remove the duplicate values from the list.

 

      This saves you the need to hit the database numerous times to fill different controls.  So you set your control up like this:

 

        Me.ddl.DataSource = Me.dsCO

        Me.ddl.DataTextField = "ENDDATE"

        Me.ddl.DataValueField = "ENDDATE"

        Me.ddl.DataBind()

 

Once you databind() the control you call this function and pass it your dropdownlist:

 

 

   Private Sub RemoveDuplicates(ByVal ddl As WebControls.DropDownList)

        If ddl.Items.Count > 0 Then

            For i As Integer = 0 To ddl.Items.Count - 1

                If Not (i >= ddl.Items.Count) Then

                    Dim duper As String = ddl.Items.Item(i).Value

                    For j As Integer = i To ddl.Items.Count - 1

                        If Not (j + 1 >= ddl.Items.Count) Then

                            If (duper = ddl.Items.Item(j + 1).Value) Then

                                ddl.Items.RemoveAt(j + 1)

                            End If

                        End If

                    Next

                End If

            Next

        End If

    End Sub

posted on Wednesday, October 13, 2004 9:26 AM

Feedback

No comments posted yet.

Post Comment

Title  
Name  
Url
Comment   
Protected by Clearscreen.SharpHIPEnter the code you see: