Reputation: 1481
I am trying to figure out something. I have a method which adds some items into a ComboBox
named "cbSize". I realize that if I add two types of data into it, the code will crash. Is this because a ComboBox
can only accommodate one type of data?
items.Add(1);
items.Add(10);
items.Add(100);
items.Add(2);
items.Add(20);
items.Add(3);
items.Add(30); //works fine if add numbers only
//items.Add("4"); //will crash if mix both numbers and text
//items.Add("2"); //works fine if add text only
//then sort them out
items.Sort();
//now clear original cbSize items
cbSize.Items.Clear();
//and add them back in sorted order
cbSize.Items.AddRange(items.ToArray());
//gotta clear ArrayList for the next time or else things will add up
items.Clear();
Upvotes: 3
Views: 410
Reputation: 63065
Is this because a ComboBox can only accommodate one type of data?
No, try below it will work
cbSize.Items.Add("44");
cbSize.Items.Add(44);
problem is with your items collection, it is type safe. you can't add different types to it.
try with list of objects. it will work. reason is both int and string are objects
List<object> items = new List<object>();
items.Add(1);
items.Add(30);
items.Add("4");
items.Add("2");
//since you have string and int value you need to create custom comparer
items.Sort((x, y) => Convert.ToInt32(x).CompareTo(Convert.ToInt32(y)));
//now clear original cbSize items
cbSize.Items.Clear();
//and add them back in sorted order
cbSize.Items.AddRange(items.ToArray());
OR you can use ArrayList class (not type-safe because it can store any object)
var integers = new ArrayList();
integers.Add(1);
integers.Add(2);
integers.Add("3");
comboBox1.Items.AddRange(integers.ToArray());
Upvotes: 2
Reputation: 8352
Yes. What you can do is to provide a Size class that will adapt from ints and strings:
items.Add(new Size(3));
items.Add(new Size(4));
items.Add(new Size("large"));
Then, you could make the Size class implement IComparable so you can call the Sort()
method.
Upvotes: 0