Hi all,
I have 2listboxes and two buttons. I am trying to move items between these listboxes using buttons. I want to avoid adding the same items more than once to any of the listboxes and here is what I am using which is not working. It just keeps adding and ignores the if statement.
if(listbox2.Items.Contains(listbox1.Items) == true)
{
MessageBox.Show("Items already added");
}
else
{
foreach(var item in listbox1.Items)//Adds ALL items that are in the listbox
{
listbox2.Items.Add(item);
}
Loading
VulpesRank #55 · 29.2K reputationPosted Jul 30, 2012, 6:13 AM EDT
for(int i = 0; i
if (!listBox2.Items.Contains(listBox1.Items[i])) listBox2.Items.Add(listBox1.Items[i]);
}
listBox1.Items.Clear(); // if you want to move rather than just copy
Satyapriya NayakRank #47 · 31.5K reputationPosted Jul 30, 2012, 4:48 AM EDT
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
listBox1.Items.Add("Raj");
listBox1.Items.Add("Raj");
listBox1.Items.Add("Raju");
listBox1.Items.Add("Rahul");
listBox1.Items.Add("Harry");
listBox1.Items.Add("Ben");
listBox1.Items.Add("Ian");
}
private void btn_right_Click(object sender, EventArgs e)
{
if (listBox2.Items.Contains(listBox1.SelectedItem) == true)
{
MessageBox.Show("Item Exits");
}
else
{
listBox2.Items.Add(listBox1.SelectedItem);
int i = 0;
i = listBox1.SelectedIndex;
listBox1.Items.RemoveAt(i);
}
}
private void btnleft_Click(object sender, EventArgs e)
{
listBox1.Items.Add(listBox2.SelectedItem);
int i = 0;
i = listBox2.SelectedIndex;
listBox2.Items.RemoveAt(i);
}
}
}
Thanks
Avuya MxoliRank #7,940 · 231 reputationPosted Jul 30, 2012, 5:39 AM EDT
Avuya MxoliRank #7,940 · 231 reputationPosted Jul 31, 2012, 12:29 AM EDT
VulpesRank #55 · 29.2K reputationPosted Jul 31, 2012, 12:38 AM EDT
Avuya MxoliRank #7,940 · 231 reputationPosted Jul 31, 2012, 12:59 AM EDT
VulpesRank #55 · 29.2K reputationPosted Jul 31, 2012, 1:12 AM EDT
var duplicateList = new List
for(int i = 0; i
if (!listBox2.Items.Contains(listBox1.Items[i]))
{
listBox2.Items.Add(listBox1.Items[i]);
}
else
{
duplicateList.Add(listBox1.Items[i].ToString());
}
}
listBox1.Items.Clear();
if (duplicateList.Count > 0)
{
MessageBox.Show("Duplicates of the following items have been removed:\r\n\r\n" + String.Join("\r\n", duplicateList.ToArray()));
}
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questionsTop experts