使用Dictionary製作兌獎器(WindowsForms)

今天要為大家介紹一個使用Dictionary物件容器的最佳時機,就是搭配Winforms的ComboBox(下拉式選單)!

那麼,我們開始製作吧!

製作兌獎器步驟:

1.在同專案下自定義Prize類別,此類別容納PrizeItem、PrizeValue屬性、Prize建構函數

  class Prize
    {
        public string PrizeItem { get; set; }
        public string PrizeValue { get; set; }
        public Prize(string item, string value)
        {
            this.PrizeItem = item;
            this.PrizeValue = value;
        }    
        
    }

2.宣告一個變數名為prizeDic的容器,然後將容器內的Key與Value初始化。

 public partial class Form1 : Form
    {
        Dictionary<int, Prize> prizeDic = new Dictionary<int, Prize>()
        {
            {1,new Prize("iPhone11","20000") },
            {2,new Prize("MacBook Air","60000") },
            {3,new Prize("Sony Bluetooth Speaker","2500") },
            {4,new Prize("XXX hairdryer","250") },
            {5,new Prize("XXX PowerBank","700") },
            {6,new Prize("Tototo StuffyToy","390") },
            {7,new Prize("hairband","160") },
            {8,new Prize("C# Tutorial Book","800") },
        };
    }

3.在Form構造函數內將prizeDic的Key,配合foreach將keys傳入ComboBox物件的Items裡

  public Form1()
        {
            //在ctor裡將combo初始化:將prizeDic集合裡的Key放入pickedNumber的items裡
            InitializeComponent();
            foreach (int keys in prizeDic.Keys)
            {
                pickedNumber.Items.Add(keys);
            }
        }

4.在ComboBox的EventHandler設定查字典的功能

private void pickedNumber_SelectedIndexChanged(object sender, EventArgs e)
        {
            //提供Key作為索引,得到傳回值prizeResult
            Prize prizeResult = prizeDic[(int)pickedNumber.SelectedItem];
            item.Text = prizeResult.PrizeItem;
            value.Text = prizeResult.PrizeValue;
        }

製作完長這樣:

如有敘述錯誤,還請不吝嗇留言指教,thanks!