In this article I’m going to explain how to add listitem from one listbox to another listbox with preventing duplicate.
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Linq;
usingSystem.Text;
usingSystem.Windows.Forms;
namespaceAddlistitemOneListboxtoAnotherListbox
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private voidForm1_Load(object sender, EventArgs e)
{
listBox1.Items.Add(“AAA”);
listBox1.Items.Add(“BBB”);
listBox1.Items.Add(“CCC”);
listBox1.Items.Add(“DDD”);
listBox1.Items.Add(“EEE”);
}
private voidbutton1_Click(object sender, EventArgs e)
{
if (listBox1.SelectedIndex>-1 )
{
string str = listBox1.GetItemText(listBox1.SelectedItem);
int idx = listBox2.FindString(str, -1);
if (idx!=-1)
{
MessageBox.Show(“Found the item – “ + str);
}
else
{
listBox2.Items.Add(listBox1.SelectedItem);
}
}
}
}
}