Search code examples
c#comboboxwindows-store-apps

Get all countries in comboBox


I want to fill the ComboBox with all the country names list by using

Using System.Globalization
Using System.Collections

here is my XAML coding for the ComboBox

<ComboBox x:Name="countryComboBox" Width="300"/>

In the C# coding I have add button. Here is that code, and I want to get the country from the ComboBox and store it in the MySql database. How can I do that?

private void addButton_Click(object sender, RoutedEventArgs e)
{
    try
    {
        string Query = @"INSERT INTO `bcasdb`.`tbl_student`
                         (`reg_id`,
                          `std_fname`,
                          `std_lname`,
                          `tbl_batch_batch_id`,
                          `gender`) 
                         VALUES (@regId, @fName, @lName, @bID, @gender, @country)";
        //This is command class which will handle the query and connection object.
        MySqlConnection conn = new MySqlConnection(BCASApp.DataModel.DB_CON.connection);
        MySqlCommand cmd = new MySqlCommand(Query, conn);
        conn.Open();
        cmd.Parameters.AddWithValue("@regId", this.regIDInput.Text);
        cmd.Parameters.AddWithValue("@fName", this.fnameInput.Text);
        cmd.Parameters.AddWithValue("@lName", this.lnameInput.Text);
        cmd.Parameters.AddWithValue("@bID", this.batchIDInput.Text);
        cmd.Parameters.AddWithValue("@gender",this.maleRadioButton);
        cmd.ExecuteNonQuery();
        conn.Close();
        successmsgBox();
    }
    catch (Exception)
    {
        errormsgBox();
    }
}

Solution

  • Code to get all Countries:

    using System.Globalization;
    using System.Runtime.InteropServices;
    
    public class LocalesRetrievalException : Exception
    {
        public LocalesRetrievalException(string message)
            : base(message)
        {
        }
    }
    
    #region Windows API
    
    private delegate bool EnumLocalesProcExDelegate(
       [MarshalAs(UnmanagedType.LPWStr)]String lpLocaleString,
       LocaleType dwFlags, int lParam);
    
    [DllImport(@"kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    private static extern bool EnumSystemLocalesEx(EnumLocalesProcExDelegate pEnumProcEx,
       LocaleType dwFlags, int lParam, IntPtr lpReserved);
    
    private enum LocaleType : uint
    {
        LocaleAll = 0x00000000,             // Enumerate all named based locales
        LocaleWindows = 0x00000001,         // Shipped locales and/or replacements for them
        LocaleSupplemental = 0x00000002,    // Supplemental locales only
        LocaleAlternateSorts = 0x00000004,  // Alternate sort locales
        LocaleNeutralData = 0x00000010,     // Locales that are "neutral" (language only, region data is default)
        LocaleSpecificData = 0x00000020,    // Locales that contain language and region data
    }
    
    #endregion
    
    public enum CultureTypes : uint
    {
        SpecificCultures = LocaleType.LocaleSpecificData,
        NeutralCultures = LocaleType.LocaleNeutralData,
        AllCultures = LocaleType.LocaleWindows
    }
    
    public static List<CultureInfo> GetCultures(CultureTypes cultureTypes)
    {
        List<CultureInfo> cultures = new List<CultureInfo>();
        EnumLocalesProcExDelegate enumCallback = (locale, flags, lParam) =>
        {
            try
            {
                cultures.Add(new CultureInfo(locale));
            }
            catch (CultureNotFoundException)
            {
                // This culture is not supported by .NET (not happened so far)
                // Must be ignored.
            }
            return true;
        };
    
        if (EnumSystemLocalesEx(enumCallback, (LocaleType)cultureTypes, 0, (IntPtr)0) == false)
        {
            int errorCode = Marshal.GetLastWin32Error();
            throw new LocalesRetrievalException("Win32 error " + errorCode + " while trying to get the Windows locales");
        }
    
        // Add the two neutral cultures that Windows misses 
        // (CultureInfo.GetCultures adds them also):
        if (cultureTypes == CultureTypes.NeutralCultures || cultureTypes == CultureTypes.AllCultures)
        {
            cultures.Add(new CultureInfo("zh-CHS"));
            cultures.Add(new CultureInfo("zh-CHT"));
        }
    
        return cultures;
    }
    
    public static List<string> GetCountries()
    {
        List<CultureInfo> cultures = GetCultures(CultureTypes.SpecificCultures);
        List<string> countries = new List<string>();
    
        foreach (CultureInfo culture in cultures)
        {
            RegionInfo region = new RegionInfo(culture.Name);
    
            if (!(countries.Contains(region.EnglishName)))
            {
                countries.Add(region.EnglishName);
            }
        }
    
        return countries;
    }
    

    How to use this code:

    You just need to call method GetCountries:

    comboBoxCountries.ItemsSource = GetCountries();
    

    Reference: Replacement for CultureInfo.GetCultures in .NET Windows Store apps