How to 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]

 
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);
			}
		}
	}
}

Author: Ankur

Have worked primarily in the domain of Calling, CRM and direct advertisers services. My technological forte is Microsoft Technologies especially Dot Net (Visual Studio 2003, 2005, 2008, 2010 and 2012) and Microsoft SQL Server 2000,2005 and 2008 R2. My Area of Expertise is in C#. Net, VB.Net, MS-SQL Server, ASP. Net, Silverlight, HTML, XML, Crystal Report, Active Reports, Infragistics, Component Art, ComponeOne, Lead Tools etc.

One thought on “How to remove duplicate items from listbox in .net”

  1. above code snippet is only for removing already existing items.
    I want to avoid duplicate records at the time of binding items to listbox at runtime…

Comments are closed.