【问题标题】:Get enum value from ComboBox and store it in integer?从 ComboBox 获取枚举值并将其存储为整数?
【发布时间】:2019-08-30 16:07:52
【问题描述】:

我有一组枚举存储一些城市的邮政编码。

public enum cities_zip
{
    Emsdetten = 48282,
    Berlin = 12345,
    Rheine = 48369,
}

我有一个组合框,其中充满了 enums,如下所示:

combo_cities.DataSource = Enum.GetValues(typeof(cities_zip));

但是,当我选择例如柏林时,它并没有被存储为整数。

int zipcode = combo_cities.SelectedValue;

它说“无法将类型对象转换为 int”。

如果我这样做:

int zipcode = Convert.ToInt32(combo_cities.SelectedValue);

无论我选择哪个城市,整数的值都是“0”。

无论我选择哪个城市,使用 SelectedIndex 都会显示为 -1。

使用SelectedItem 也不起作用(也显示为“0”)。

有什么建议吗?

【问题讨论】:

  • 确认一下,这是winforms,对吧?您所描述的 SelectedIndex 为 -1,听起来好像没有选定项目。在测试代​​码中,据我所知(并没有太多),这对我有用:在 SelectedIndexChanged 中,int x = (int)(sender as ComboBox).SelectedItem; 让我获得所选枚举值的 int 值。
  • 当使用枚举时,SelectedValue 将给您Enum.ToString(),而(int)SelectedValue 将返回相关值(此处为int)。在这种情况下,同样适用于SelectedIem。如果您在选择后得到SelectedIndex = -1,那么您做错了此处未显示的错误。
  • @Jimi SelectedValue 并非如此。如果 ValueMember 没有设置,它会返回实际的枚举值,和 SelectedItem 一样。
  • @Ed Plunkett 重读评论,我可能表达的概念过于松散。 SelectedItemSelectedValue 都返回一个 Enum 作为对象。如果您inspectprint 它,您将看到[Enum].ToString()。您可以将关联的值转换为它的值类型。
  • @Jimi 谢谢,这更清楚了。

标签: c# winforms enums combobox


【解决方案1】:

我想这个例子将有助于理解:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        comboBox1.DisplayMember = "CityName";
        comboBox1.ValueMember = "CityValue";
        comboBox1.DataSource = ListOfCities();
    }
    public List<City> ListOfCities()
    {
        List<City> list = new List<City>();
        foreach (cities_zip city in Enum.GetValues(typeof(cities_zip)))
        {
            City newCity = new City();
            newCity.CityName = city.ToString();
            newCity.CityValue = (int)city;
            list.Add(newCity);
        }
            return list;
    }
}    
public class City
{
    public string CityName { get; set; }
    public int CityValue { get; set; }
}
public enum cities_zip
{
    Emsdetten = 48282,
    Berlin = 12345,
    Rheine = 48369,
}

【讨论】:

    【解决方案2】:

    简单的(int)combo_cities.SelectedValue 就可以了。

    但您还需要检查SelectedIndex 是否不同于-1,因为这意味着没有选择任何项目。像这样的:

    if( combo_cities.SelectedIndex > -1)
        var selectedIntValue = (int)combo_cities.SelectedValue;
    

    要使上述工作,您必须调用:

    foreach (Subject s in Enum.GetValues(typeof(cities_zip)).Cast<cities_zip>())
        cbxSubject.Items.Add(s);
    

    而不是设置DataSource 属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多