Click here to Skip to main content
15,896,063 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hey guys,

Whats the best way to handle ComboBox Text values that need to translate into an integer.

For example if I have a Combobox with 15 or so items, labeled "Item A", "Item B", "Item C", etc. and each one of those need to be translated to an integer, such as Item A = 1016, Item B = 2422, Item C = 8471.

Is the best way to do that a big long list of "Else IF"?
C#
if (comboBox1.SelectedIndex = 0)
       {
           itemNum = 1016;
       }
   else if (comboBox1.SelectedIndex = 1)
       {
           itemNum = 2422;
       }
   else if (comboBox1.SelectedIndex = 2)
       {
           itemNum = 8471;
       }

It works, but it just doesn't seem to be very efficient if I have a lot of items.
Posted
Comments
joshrduncan2012 7-Oct-13 16:21pm    
Maybe a switch statement?
Azee 7-Oct-13 16:29pm    
Didn't you try binding those Values against the Texts with the ComboBox and try SelectedValue to get the Values?
Sergey Alexandrovich Kryukov 7-Oct-13 16:39pm    
Apparently, your code is not supportable, so your idea to seek an advice is really good. Only, when you say, "ComboBox", the question is: which one? If you tell me what is it, most likely, I have a comprehensive answer for you. Note that when it comes to UI, you always need to tag the UI library or application type you are using.
—SA
Delurn 7-Oct-13 16:55pm    
this is a .Net4.5 WPF combobox
Sergey Alexandrovich Kryukov 7-Oct-13 17:43pm    
Good, but please add the tag "WPF" to your question.

Very good, now my comprehensive answer I promised is ready; please see Solution 3. (Note that Solution 2 will work too, but this approach is somewhat more bulky and indirect.)

Your follow-up questions are welcome.
—SA

For contrast to the fine code examples provided by SAK and Idenizeni, here's the "lazy programmer's way" in WinForms:
C#
private int ItemNumber;

private List<string> cmbItemList = new List<string> { "A", "B", "C", "D" };

private List<int> cmbItemCode = new List<int> { 1016, 2422, 8471, 1234 };

private void FormTemplate_Load(object sender, EventArgs e)
{
    comboBox1.Items.AddRange(cmbItemList.Cast<object>().ToArray());
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    ItemNumber = cmbItemCode[comboBox1.SelectedIndex];

    // for testing only
   Console.WriteLine(ItemNumber);
}
 
Share this answer
 
v4
Comments
Sergey Alexandrovich Kryukov 7-Oct-13 23:16pm    
I voted 5, mostly for admitting this approach as being "lazy". :-)
The value of it is this: sometimes you deal with containers like those UI control wrappers, which are designed less accurately than those of System.Windows.Forms and WPF (and how good a those is still a matter of discussion). In such cases, in a pinch, one could use something similar to your code sample, as a workaround.

One note: underscores and "somboBox1" violate (pretty good, I would say) Microsoft naming conventions. There are the artifact of not using refactorization engine to give everything some semantic names. Auto-generated names cannot be good enough by definition, and "=+" are not shown, so, from your sample, it is not 100% obvious that "comboBox1_SelectedIndexChanged" is an event handler. So, I would advise to show the self-containing "+= (sender, eventArgs) => { ... }" or "+= delegate (object sender, MyEventArgs eventArgs)" syntax, which is also better in real-life development in many cases (also can be a subject of discussion though)...

—SA
Delurn 9-Oct-13 15:52pm    
Thanks Bill. I appreciate all of the ways that have been explained. Each one can be used for different types of projects or even different objectives within the same project.
Here is what I advise to do: don't store strings in the combo box items. Who told you that you need to have strings? The runtime type of the list element is System.Object:
http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.objectcollection.add.aspx[^],
http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.objectcollection.aspx[^],
http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.objectcollection.add.aspx[^].

Use any custom object, of some class or structure you can design to encapsulate all the detail on each item required by your functionality. The only problem is: what will be displayed in the UI for each item? The answer is simple: whatever the function ToString() returns. So, you have to override System.Object.ToString(). For example:

C#
internal class MyComboBoxItem {
    internal MyComboBoxItem(string title, int itemNumber /* , some more property initial values... */) {
        this.Title = title;
        this.ItemNumber = itemNumber;
        // more initializations
    } //MyComboBoxItem
    internal int ItemNumber { get; set; }
    internal string Title { get; private set; }
    public override string ToString() {
        return Title;
    } //System.Object.ToString
    //...
} //class MyComboBoxItem


Now, you can add any number of the objects of the class shown above. During runtime, you will be able to reduce all your switch statement (unsupportable, totally unsupportable) to just a few lines, regardless of the actual number of items:
C#
myComboBox.Items.Add(new MyComboBoxItem("Some item title", someIntegerValueForItemNumber /* , some more property initial values... */));

//...

if (myComboBox.SelectedItem != null) {
    MyComboBoxItem item = (MyComboBoxItem)myComboBox.SelectedItem;
    // now, all non-private members of items are accessible
    int itemNum = item.ItemNumber;
    // and so on...
} //if


Are you getting the idea?

—SA
 
Share this answer
 
v2
Comments
idenizeni 7-Oct-13 18:45pm    
+5ed. This is a nice solution.
Sergey Alexandrovich Kryukov 7-Oct-13 19:20pm    
Thank you very much.
—SA
BillWoodruff 7-Oct-13 20:03pm    
+5 excellent answer
Sergey Alexandrovich Kryukov 7-Oct-13 20:25pm    
Thank you, Bill.
—SA
Ron Beyer 7-Oct-13 21:20pm    
+5'd, this is exactly why the Items property is a collection of objects and not text :)
C#
// create a class to use for the item pairs
class ComboBoxItem
{
    public ComboBoxItem(int itemID, string itemText)
    {
        ItemID = itemID;
        ItemText = itemText;
    }

    public int ItemID { get; set; }
    public string ItemText { get; set; }

}


// in our WPF window populate a list of combobox items, set combobox properties and reference list of item

        public MainWindow()
        {
            InitializeComponent();

            // set combobox properties
            comboBox1.SelectedValuePath = "ItemID";
            comboBox1.DisplayMemberPath = "ItemText";
            comboBox1.ItemsSource = CreateItemPairs();
            comboBox1.SelectedIndex = -1; 
        }

        // handle selection changed event
        private void comboBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            int itemNum = 0;
            if (comboBox1.SelectedIndex > -1)
            {
               Int32.TryParse(comboBox1.SelectedValue.ToString(), out itemNum);
               
                MessageBox.Show(itemNum.ToString());
            }
        }

// populate items list
private List<ComboBoxItem> CreateItemPairs()
{
    List<ComboBoxItem> comboItems = new List<ComboBoxItem>();

    comboItems.Add(new ComboBoxItem(1111, "Item A"));
    comboItems.Add(new ComboBoxItem(2222, "Item B"));
    comboItems.Add(new ComboBoxItem(3333, "Item C"));

    return comboItems;
}
 
Share this answer
 
v4
Comments
Sergey Alexandrovich Kryukov 7-Oct-13 17:45pm    
Did you try it by yourself? Everything is correct, except one critical detail: all your items with show the text "ComboBoxItem" instead of item text. Without the fix, your code is not useful.
The solution is simple. Please see Solution 3.

Also, the list of ComboBoxItem is totally redundant. Finally, your code won't even compile, because of casing... Sorry, this is miss... :-)

—SA
idenizeni 7-Oct-13 18:14pm    
Yes, I tested it before I posted it and it worked as expected; the value was shown and not the text "ComboBoxItem". I see now that the <comboboxitem> text is not properly cased, this must have happened when I edited the solution here because it was properly cased in my test.
Sergey Alexandrovich Kryukov 7-Oct-13 18:17pm    
I'll repeat: it won't even compile. I did not see the code which worked, but it could not be the code you published.
And even "it worked" would not be enough. Unacceptable code, face it.
—SA
idenizeni 7-Oct-13 18:20pm    
You are too fast, I just reposted the code to fix the issues I think you encountered. I am guessing the previous code did't compile because this line...
List<comboboxitem> comboItems = new List<comboboxitem>();
The <> brackets freaked the CP editor out and made the items lowercase.
Sergey Alexandrovich Kryukov 7-Oct-13 19:20pm    
I see, thank you for the note, but I without ToString it won't show correct strings in the UI...
—SA

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