Click here to Skip to main content
15,895,370 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
Im using a dropdown list to add the items to the listbox
Posted
Comments
BillWoodruff 14-Oct-11 19:23pm    
+5 for a question that, while it left us to guess what the actual use case was, still provoked a most interesting set of answers, and discussions.
I.explore.code 14-Oct-11 19:27pm    
Indeed. My virtual 5+ for that... ;)

Even simpler code without loops:

C#
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
   //check if the item exists already and only add if it doesn't
   if (listBox1.Items.IndexOf(comboBox1.SelectedItem.ToString()) == -1)
   {
      listBox1.Items.Add(comboBox1.SelectedItem.ToString());
   }
}
 
Share this answer
 
Comments
I.explore.code 14-Oct-11 18:34pm    
As an alternative:

if (!listBox1.Items.Contains(comboBox1.SelectedItem.ToString()))
{
listBox1.Items.Add(comboBox1.SelectedItem.ToString());
}
BillWoodruff 14-Oct-11 19:21pm    
+5 for solid, time-tested, solution.
I.explore.code 14-Oct-11 19:27pm    
lol... thanks mate!
Here the lamda expression version

 if ((listBox1.Items.Cast<string>().ToList())
             .Where(c => c == textBox1.Text).Count() == 0)
                    listBox1.Items.Add(textBox1.Text); 
</string>
 
Share this answer
 
Comments
I.explore.code 14-Oct-11 18:24pm    
I am sorry mate, doesn't seem to work either, looks like for something so simple trying to use Lambda is an overkill...
Bala Selvanayagam 14-Oct-11 20:17pm    
How did you decide this does not work ?
Member 14831240 5-Aug-20 7:48am    
Perfect solution !
Try this:

C#
if(listBox1.FindString(DropDownlist1.Text)!=-1)
{
listBox1.Items.Add(DropDownlist.Text);
}
 
Share this answer
 
v2
Comments
I.explore.code 14-Oct-11 11:58am    
HAHA! loads of ways of doing the same thing! programming is awesome :) I am sure there is a way of using lambda expressions and LINQ to do this as well...
[no name] 14-Oct-11 16:28pm    
What like this:

if(listBox1.Items.SingleOrDefault(item => item == DropDownlist1.Text) == null)
{
listBox1.Items.Add(DropDownList.Text);
}

;-D
I.explore.code 14-Oct-11 18:12pm    
I am afraid Collin, it doesn't work. I think you would need to cast the Items collection to Enumerable first and then you can use lambdas...
I know this has been solved, but just thought of sharing this solution which is a bit of hack too only for the mates that have tried to use Lambdas as above:

C#
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            listx.Add(comboBox1.SelectedItem.ToString());
            listBox1.Items.Clear();
            listBox1.Items.AddRange(listx.Distinct().ToArray());
        }



listx is just a
C#
List<string>
defined at the page level, instead of directly adding to the listbox we add it in the list (this will have duplication) but then using the Distinct() method we can just retrieve the unique ones and add all of them to the listbox in one go. Ofcourse, we need to clear the listbox everytime so this may not be the most efficient way as we are storing the items in a temporary list as well, but I think its still better than having loops.

Cheers...

EDIT: DON'T USE THIS SOLUTION, I TIMED THIS CODE FOR 3000 ELEMENTS AND TOWARDS THE END IT WAS ALREADY TAKING ROUGHLY 47MS WHICH IS 47 TIMES SLOWER THAN USING INDEXOF OR CONTAINS (WHICH ARE THE FASTEST)
 
Share this answer
 
v2
Lots of good solutions here !

An out-of-the-box idea (requires a reference to Linq): based on the assumption that the when the OP says "I'm using a drop-down list" as the source of new items he means: there is a ComboBox which is the source of new items for a ListBox.

0. pre-parse the ComboBox Items and eliminate duplicates ... if there could be duplicates.
XML
List<object> noDup = comboBox1.Items.Cast<object().Distinct().ToList();
comboBox1.Items.Clear();
noDup.ForEach(itm => comboBox1.Items.Add(itm));
1. every time the user selects one item from the ComboBox drop-down to add, remove that item from the ComboBox items
private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
{
    listBox1.Items.Add(comboBox1.SelectedItem);
    comboBox1.Items.Remove(comboBox1.SelectedItem);
}
And, yes, I do think end-users might find it a bit strange that the ComboBox Items' list 'shrinks' as they make selections to populate the ListBox :)
 
Share this answer
 
v3
Comments
I.explore.code 14-Oct-11 19:12pm    
well, yeah this could be the other way it depends what the users want really. This probably would be the safest which removes the remotest possibility of duplication. But if the users still want to be able to access the items from the dropdown, then as you say they might find it strange :)
BillWoodruff 14-Oct-11 19:19pm    
It would be interesting, if you have time, to know the time performance of this solution compared to your other solution timings. I could see this solution used in the case where you move things back and forth between two lists. And, since you have the no-duplicate list created here, you could always reset the ComboBox Items from that.
I.explore.code 14-Oct-11 19:33pm    
yeah, although something tells me that if that would be the scenario then instead of using combo box i would much rather use another listbox to move things "back and forth". Just about usability really, this one. The questioner has already opted for a "loopy" answer ;)...
BillWoodruff 14-Oct-11 19:46pm    
Yes, I agree with you. The only scenario I can imagine where I'd go for something like this would be where you'd have two ListBoxes and you could move items back and forth between them ... and, if you deleted items, from either ListBox, then they might go in a ComboBox, where, if selected, they would then be inserted in the last ListBox that had focus. But, again, this was just an experiment in thinking out-of-the-box and refreshing my memory on how to use 'Distinct in Linq :)
I.explore.code 14-Oct-11 19:41pm    
oh and I don't really think that your solution is anywhere near as slow as a loop based solution, since you are removing the items from the combo-box. So Essentially, your add and remove are constant time operations which is good.
Just check whether it's already in the list. Code similar to this in the method that adds items to the list should do the trick:

C#
bool found;
for (int i = 0; i < myListBox.Items.Count; ++i)
{
    if (myListBox.Items[i] == myComboBox.Text)
        found = true;
}
if(!found)
    myListBox.Items.Add(myComboBox.Text);
 
Share this answer
 
v2
Comments
I.explore.code 14-Oct-11 19:02pm    
i tested your code and my code too for time performance, data is:
YOUR CODE
items in combo: 3000
search time taken towards the 3000th iteration: approx. 14ms

MY CODE
items in combo: 3000
search time taken towards the 3000th iteration: approx. 1ms

so roughly 14 times speed gain if you don't use loops, in the worst case. Please don't take it the wrong way, its just for sharing information and ideas and solutions and making them better.
Macro Man 17-Oct-11 4:46am    
Always happy to learn! However it is rather depressing that mine is almost the slowest solution here. :'(

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