Click here to Skip to main content
15,891,864 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
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);
}
}
Posted

C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void bttnAdd_Click(object sender, EventArgs e)
        {
            for (int __k = 0; __k < lst_1.Items.Count; __k++)
            {
                if (lst_2.Items.Contains(lst_1.Items[__k]))
                    cbo.Items.Add(lst_1.Items[__k]);
            }
        }
    }
}
 
Share this answer
 
by using System.Linq

C#
var list1 = lbFirstTableColumns.Items.Cast<string>();
var list2 = lbSecondTableColumns.Items.Cast<string>();


cbo.DataSource = list1.Intersect(list2);
 
Share this answer
 
v2
Comments
Member 9975733 20-Dec-13 12:39pm    
Please code for C# Web application

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900