Compare Listboxes

I have to listboxes. I need to check them for differences. How would I check them and if an item is new or different, display that item?
XGenwareSAsked:
Who is Participating?
 
Fernando SotoConnect With a Mentor RetiredCommented:
Hi XGenwareS;

OK, try this.

Fernando
Imports System.Text

Dim lb1 As List(Of String) = ListBox1.Items.Cast(Of Object)().Select(Function(s) s.ToString()).ToList()
Dim lb2 As List(Of String) = ListBox2.Items.Cast(Of Object)().Select(Function(s) s.ToString()).ToList()

Dim lbDiff As List(Of String) = lb1.Except(lb2).ToList()

Dim stringDiff As New StringBuilder()
lbDiff.ForEach(Function(s) stringDiff.Append(s & vbCrLf))

MessageBox.Show(stringDiff.ToString())

Open in new window

0
 
magdy99Commented:
use another listbox listbox3 for example and button  and put the following code

 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim count As Integer
        count = ListBox2.Items.Count


        For i As Integer = 0 To count - 1
            Dim item As Object = ListBox1.Items.Item(i)
            If Not ListBox2.Items.Contains(item) Then
                ListBox3.Items.Add(item)
            End If


        Next
0
 
Fernando SotoRetiredCommented:
Hi XGenwareS;

More info would be helpful. What version of .Net Framework and Visual Studio? What is being assigned to the ListBox, String data or Class Object?

Fernando
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

 
XGenwareSAuthor Commented:
I am using .Net 3.5 And Visual Studio 2008. I am assigning string data to the Listbox.
0
 
Fernando SotoRetiredCommented:
Hi XGenwareS;

Because you are using the .Net Framework 3.5 you can use Linq to solve your issue. The list of strings in lbDiff in the code snippet will contain the difference between the two list boxes.

Fernando
Dim lb1 As List(Of String) = ListBox1.Items.Cast(Of Object)().Select(Function(s) s.ToString()).ToList()
Dim lb2 As List(Of String) = ListBox2.Items.Cast(Of Object)().Select(Function(s) s.ToString()).ToList()

Dim lbDiff As List(Of String) = lb1.Except(lb2).ToList()

Open in new window

0
 
XGenwareSAuthor Commented:
Alright that appears to work. Now how would I display the items in lbDiff in say a messagebox?
0
 
XGenwareSAuthor Commented:
Worked Perfectly
0
 
Fernando SotoRetiredCommented:
Very good, glad I was able to help.  ;=)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.