WinForm in ComboBox with each other enumeration class assignment

Enum class

Test enumerated classes - City

/// <summary>
/// 城市
/// </summary>
public enum City
{
    HangZhou = 1,
    BeiJing = 0,
    ShangHai = 2,
    ShenZhen = 3
}

winform simple setup

Add in a form design ComboBoxnamed Cmb_City
editor Constructor

/// <summary>
/// 构造函数
/// </summary>
public Form1()
{
    InitializeComponent();
    //将枚举赋值到ComboBox中
    Cmb_City.DataSource = Enum.GetNames(typeof(City));
}

Results are as follows:
Here Insert Picture Description

Selected items into the corresponding enumeration object

Increase ComboBoxof SelectedIndexChangedevents

public partial class Form1 : Form
{
   /// 构造函数
   public Form1(){...}
   
   /// 枚举属性
   public City city { get; set; }
   
   /// <summary>
   /// 更改选项时触发
   /// </summary>
   /// <param name="sender"></param>
   /// <param name="e"></param>
   private void Cmb_City_SelectedIndexChanged(object sender, EventArgs e)
   {
       city = (City)(Enum.Parse(typeof(City), Cmb_City.Text, true));
   }

   /// 城市
   public enum City{...}
}
Published 62 original articles · won praise 68 · views 160 000 +

Guess you like

Origin blog.csdn.net/ZUFE_ZXh/article/details/103959461