有了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);