:::: MENU ::::

Monday, September 27, 2010

Most projects I work on need a list of countries at some point so I put together a snippet of SQL that I could reuse to create and populate a countries table in the database with all countries as given in ISO 3166-1. After recently writing a utility class to populate list controls with world currencies according to ISO 4217 it got me wondering if I could also do the same for countries using only the .Net Framework. And so I came up with the following utility class to do the job.

        /// <summary>
        /// Populates the list control with countries as given by ISO 4217.
        /// </summary>
        /// <param name="ctrl">The list control to populate.</param>
        public static void FillWithISOCountries(ListControl ctrl)
        {
            foreach (CultureInfo cultureInfo in CultureInfo.GetCultures(CultureTypes.SpecificCultures))
            {
                RegionInfo regionInfo = new RegionInfo(cultureInfo.LCID);
                if (ctrl.Items.FindByValue(regionInfo.TwoLetterISORegionName) == null)
                {
                    ctrl.Items.Add(new ListItem(regionInfo.EnglishName, regionInfo.TwoLetterISORegionName));
                }
            }
 
            RegionInfo currentRegionInfo = new RegionInfo(CultureInfo.CurrentCulture.LCID);
 
            //- Default the selection to the current cultures country
            if (ctrl.Items.FindByValue(currentRegionInfo.TwoLetterISORegionName) != null)
            {
                ctrl.Items.FindByValue(currentRegionInfo.TwoLetterISORegionName).Selected = true;
            }
        }

More Info