获取comboBox中的所有国家/地区

时间:2014-10-11 06:30:55

标签: c# combobox windows-store-apps

我想使用

在ComboBox中填入所有国家/地区名称列表
Using System.Globalization
Using System.Collections

这是我对ComboBox的XAML编码

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

在C#编码中我添加了按钮。这是代码,我想从ComboBox获取国家并将其存储在MySql数据库中。我怎么能这样做?

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();
    }
}

3 个答案:

答案 0 :(得分:2)

你可以像这样填充Combobox,

添加using System.Globalization

像这样设置Combobox ItemsSource,

countryComboBox.ItemsSource = GetCountryList();

public static List<string> GetCountryList()
{
    List<string> cultureList = new List<string>();

    CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures);

    foreach (CultureInfo culture in cultures)
    {
        RegionInfo region = new RegionInfo(culture.LCID);

        if (!(cultureList.Contains(region.EnglishName)))
        {
            cultureList.Add(region.EnglishName);
        }
    }
    return cultureList;
}

您可以获取selectedItem并使用查询

传递它
cmd.Parameters.AddWithValue("@country", this.countryComboBox.SelectedItem.ToString());

修改 您已经提到它适用于Windows应用商店应用,请检查此链接。如何加载国家/地区

Replacement for CultureInfo.GetCultures in .NET Windows Store apps

如果没有,您必须编写一种自定义方式从数据库加载国家/地区。

答案 1 :(得分:1)

获取所有国家/地区的代码:

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;
}

如何使用此代码:

您只需要调用方法GetCountries

comboBoxCountries.ItemsSource = GetCountries();

参考:Replacement for CultureInfo.GetCultures in .NET Windows Store apps

答案 2 :(得分:0)

此方法将返回所有国家的已订购列表:

public static List<string> GetAllCountrysNames()
{
    CultureInfo[] cultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures);

    var rez = cultures.Select(cult => (new RegionInfo(cult.LCID)).DisplayName).Distinct().OrderBy(q => q).ToList();

    return rez;
}

如果需要,您也可以将DisplayName替换为EnglishName


countryComboBox.Items.AddRange(GetAllCountrysNames());