Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

How to Add the Contents of a Generic List of String to a ComboBox

4.47/5 (7 votes)
14 Nov 2015CPOL 11K  
Adding the contents of a generic list to a combobox with one line of code

Use Generic Lists for Maintainability and Geekworthiness

Rather than entering combobox values in the designer, it is easier to maintain and more "programmer-like" to add the values in code and then access them. Additionally, by having the list in one place, you can access it from other methods when necessary, thus staying true to the DRY (Don't Repeat Yourself) Principle.

Here's how to do it; first, add the generic list of string, perhaps to a "consts/utils" class:

C#
public static List<string> Months = new List<string>
    {
       "Jan",
       "Feb",
       "Mar",
       "Apr",
       "May",
       "Jun",
       "Jul",
       "Aug",
       "Sep",
       "Oct",
       "Nov",
       "Dec"
};

And here's how you add those strings to a combobox:

C#
comboBoxMonth.Items.AddRange(UsageRptConstsAndUtils.Months.ToArray<object>());

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)