Search code examples
c#winformscomboboxlistbox

how to compare two listbox items and add common items to another combo box?


I am new to C#. I have two ListBoxes

                1 listbox    -->  lbFirstTableColumns
                2 listbox    -->  lbSecondTableColumns
                combo Box    -->  cmbJoinColumn

now I want compare two ListBox items and add to cmbJoinColumn which are common in my Listboxes

I have tried following code but it doesn't give any result

 public void AddJoinColumns()
 {
     try
     {
          List<string> lstArray = new List<string>();
          //add each items to lstarray
          for (int index = 0; index < lbFirstTableColumns.Items.Count;     index++)
          {
               lstArray.Add(lbFirstTableColumns.Items[index].ToString());
          }
          //compare each listarray item in second listbox if any matching  copy into combo box
          foreach (string str in lstArray)
          {
              MessageBox.Show(str);
              if (lbSecondTableColumns.Items.Contains(str))
              {
                  cmbJoinColumn.Items.Add(str);
              }
          }
      }
      catch (Exception ex)
      {
           MessageBox.Show(ex.Message);
      }
  } 

Solution

  • I hope this will do the trick.. though it is long process and old fashioned.

    cmbJoinColumn.Items.Clear() //If you want to remove previous Items.
    for(int intCount = 0; intCount < lbFirstTableColumns.Items.Count;intCount++)
      {
           for(int intSubCount = 0;intSubCount < lbSecondTableColumns.Items.Count; intSubCount++)
           {
                if (lbSecondTableColumns.Items[intCount].ToString() == lbSecondTableColumns.Items[intSubCount].ToString())
                 {
                      cmbJoinColumn.Items.Add(lbSecondTableColumns.Items[intCount].ToString());
                 }
           }
     }