ASP.NET - listboxes comparison - Asked By svm satya on 10-May-12 11:31 AM

hi,

i want to comparetwo listboxes and display un matched list items .can give some code.
Neha Garg replied to svm satya on 10-May-12 12:24 PM
Hi svm,

See the below example:

Suppose for example you had this:
 
 string[] city1 = { "Vancouver", "Richmond", "Delta", "Abbotsford", "Kelowna"};
 string[] city2 = { "Vancouver", "Richmond", "Delta", "Surrey", "Burnaby", "Coquitlam", "Mission" };
 listBox1.Items.AddRange(city1);
 listBox2.Items.AddRange(city2);
then "Surrey", "Burnaby", "Coquitlam" and "Mission" would appear in the difference but "Abbotsford" and "Kelowna" would not.

You can deal with this problem by adding an additional foreach loop to Shrikant's code as follows:

 foreach (var objLI in listBox1.Items)
 {
  if (!listBox2.Items.Contains(objLI))
    listBox4.Items.Add(objLI); // Different List  
 }

hope it helps..
Neha Garg replied to svm satya on 10-May-12 12:26 PM
svm,

see one more example of it:

public Form1()
{
InitializeComponent();
listBox1.Items.AddRange(new string[] { "a", "b", "c" });
listBox2.Items.AddRange(new string[] { "a", "c", "d", "e" });
}
private void button1_Click(object sender, EventArgs e)
{
List<string> list1 = new List<string>();
List<string> list2=new List<string>();
foreach (string item in listBox1.Items)
list1.Add(item);
foreach (string item in listBox2.Items)
list2.Add(item);
//newList will include all the common data between the 2 lists
var diff1 = list1.Intersect(list2);
StringBuilder sb = new StringBuilder();
sb.AppendLine("All common items from both lists:");
foreach (var item in diff1)
sb.AppendLine(item);
var a = list1.Except(list2).ToList();
var b = list2.Except(list1).ToList();
var diff2 = a.Union(b);
sb.AppendLine("\nAll different items fom both lists:");
foreach (var item in diff2)
sb.AppendLine(item);
MessageBox.Show(sb.ToString());
}
Venkat K replied to svm satya on 10-May-12 12:28 PM

Iterate through the Items of listbox1 and use the contains function to identify whether it exists in the second listbox. Here i am adding all the unmatched item in listbox4
foreach (string item in listBox1.Items)
{
  if (listBox2.Items.Contains(item))
  {
    listBox3.Items.Add(item);  // similar items
  }
  else
  {
    listBox4.Items.Add(item);  // dissimilar items
  }
}

Hope this helps!
kalpana aparnathi replied to svm satya on 10-May-12 02:13 PM
hi,

Use below code:

maint1_beDataSet.vehiclelistRow dr = default(maint1_beDataSet.vehiclelistRow);
VehiclesDataSet.VListRow ds = default(VehiclesDataSet.VListRow);

foreach ( ds in this.VehiclesDataSet.VList)
{
    this.ListBox2.Items.Add(ds.UnitNumber);

}
this.ListBox1.DataSource = null;
this.ListBox1.Items.Clear();

foreach ( dr in this.Maint1_beDataSet.vehiclelist)
{
    if (this.ListBox2.Items.Contains(dr.VehicleNumber))
    {

    }
    else
      {
        this.ListBox1.Items.Add(dr.VehicleNumber);

    }

}

Regards,