C# combined items in listbox

if item in listbox is the same, den combined them

Page 1 of 1

1 Replies - 1330 Views - Last Post: 16 January 2010 - 10:18 PM Rate Topic: -----

#1 andylsbc6  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 15-January 10

C# combined items in listbox

Posted 16 January 2010 - 09:24 PM

hi, in my form i have a button, label and 2 listboxes. And in my 1st listbox i have items like chicken, vegetables, orange,etc.
when i select the same item in the 1st listbox, how the label originally is 1 became 2...and i dont want the same item to be appear on the 2nd listbox....this code should seems easy but i am a beginner just learning..any help is appreciated thank you...=))


  private void btnAdd_Click(object sender, EventArgs e)
		{

			if (listbox1.SelectedItem != null)
			{
				listbox2.Items.Add(listbox1.SelectedItem);

			}
			else
			{
				MessageBox.Show("Please Select At least 1 item(s) to Add");
			}
		}


This post has been edited by andylsbc6: 16 January 2010 - 09:26 PM


Is This A Good Question/Topic? 0
  • +

Replies To: C# combined items in listbox

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4332
  • View blog
  • Posts: 12,127
  • Joined: 18-April 07

Re: C# combined items in listbox

Posted 16 January 2010 - 10:18 PM

Well one way you could do this is simply check if the second listbox contains the value using the contains() method of items and then remove it...

// Check if we have a selected item in first box
if (listBox1.SelectedItem != null) {

	 // Look for it in the second box and if found, remove it.
	 if (listBox2.Items.Contains(listBox1.SelectedItem)) {
		  listBox2.Items.Remove(listBox1.SelectedItem);
	 }
}



Another way you could do this is simply to loop through the second listbox and compare each value to the value of the first listbox. If the two match, then remove that item from the second listbox. It is a bit more work to do that, but can also be useful if you were storing custom objects and wanted to compare objects on different values.

:)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1