Remove duplicate items from listbox in .NET


Many times when we bind our controls from a non primary column of table then it may be a case that we got the duplicate records in our dataset. There is no sense to bind duplicate records without any identity value in any control.

With the help of the following function you can easily remove duplicate items from your Listbox control.

[VB.Net]

Private Sub RepoveDuplicate()
    For Row As Int16 = 0 To MyListBox.Items.Count - 2
        For RowAgain As Int16 = MyListBox.Items.Count - 1 To Row + 1 Step -1
            If MyListBox.Items(Row).ToString = MyListBox.Items(RowAgain).ToString
Then
                MyListBox.Items.RemoveAt(RowAgain)
            End
If
        Next
    Next
End Sub

[C#]

   
private void RepoveDuplicate()
    {
        for (Int16 Row = 0; Row <= MyListBox.Items.Count - 2; Row++)
        {
            for (Int16 RowAgain = MyListBox.Items.Count - 1; RowAgain >= Row + 1;
                 RowAgain += -1)
            {
                if (MyListBox.Items(Row).ToString == MyListBox.Items(RowAgain).ToString)
                {
                    MyListBox.Items.RemoveAt(RowAgain);
                }
            }
        }
    }