Enum和單選框關聯

來源:互聯網
上載者:User

有了enum我們可以列舉類型了,有了單選框和複選框我們可以滑鼠來選擇了。但是編程的時候覺得讓兩個關聯起來,寫代碼比較麻煩,所以想自動的關聯起來。所以我嘗試了一下,記錄如下。

假如一個星期的enum:

    public enum 星期
    {
        星期一 = 0,
        星期二,
        星期三,
        星期四,
        星期五,
        星期六,
        星期天
    }

關聯到7個RadioButton,也就是單選框。

第一步在enum中定義星期一=0

第二步在初始化函數中如下定義:

public MainForm()
        {
            //
            // The InitializeComponent() call is required for Windows Forms designer support.
            //
            InitializeComponent();
            
            //
            // TODO: Add constructor code after the InitializeComponent() call.
            //
            int idx = 0;
            foreach(Control c in groupBox1.Controls)
            {
                if(c is RadioButton)
                {
                    ((RadioButton)c).Text  = ((星期)idx).ToString();
                    ((RadioButton)c).Tag = ((星期)idx);
                    idx++;
                }
            }
        }

第三步添加測試代碼:

void Button1Click(object sender, EventArgs e)
        {
            foreach(Control c in groupBox1.Controls)
            {
                if(c is RadioButton)
                {
                    if(((RadioButton)c).Checked == true)
                    {
                        星期 week = (星期)(((RadioButton)c).Tag);
                        MessageBox.Show(week.ToString());
                    }
                }
            }

        }

注意:groupbox中控制項的順序在這些代碼中控制,假如發現順序不對,就要重新調整一下。

            this.groupBox1.Controls.Add(this.radioButton1);
            this.groupBox1.Controls.Add(this.radioButton2);
            this.groupBox1.Controls.Add(this.radioButton3);
            this.groupBox1.Controls.Add(this.radioButton4);
            this.groupBox1.Controls.Add(this.radioButton5);
            this.groupBox1.Controls.Add(this.radioButton6);
            this.groupBox1.Controls.Add(this.radioButton7);

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.