Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# WinForm
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 lstArray = new List();
//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 15-Nov-12 17:34pm
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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]);
            }
        }
    }
}
  Permalink  
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

by using System.Linq
 
var list1 = lbFirstTableColumns.Items.Cast<string>();
var list2 = lbSecondTableColumns.Items.Cast<string>();
 

cbo.DataSource = list1.Intersect(list2);
  Permalink  
v2
Comments
Member 9975733 at 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)



Advertise | Privacy | Mobile
Web03 | 2.8.141022.2 | Last Updated 16 Nov 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100