65.9K
CodeProject is changing. Read more.
Home

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

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.47/5 (7 votes)

Nov 14, 2015

CPOL
viewsIcon

11002

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:

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:

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