如果你總是要if(raidiobutton1.checked) 來判斷 太累了
方法一:
使用:
foreach(Control c in Controls)
if(c is checkBox )
if((控件屬性)c屬性條件判斷)
初加載時,預選的radioButton (但一定要小心
Trim()
如果有空格要除去)
foreach(Control c in Controls)
{
if (c is RadioButton)
{
if ((((RadioButton)c).Text).Equals(tspec))
((RadioButton)c).Checked = true;
else ((RadioButton)c).Checked = false;
}
}
得到選中的RadioButton的文本內容
string tspec="";
foreach(Control c in Controls)
{
if(c is RadioButton)
{
if (((RadioButton)c).Checked)
tspec = ((RadioButton)c).Text;
}
}
方法二
使用控件數組
RadioButton[] rb = new RadioButton[3];全局變量
如果是要預加載初始化不能放到Load中,尤其是使用showDialog跳轉窗口的(此時才執行Load方法)
再初始化方法中
public teacherInfo(string TNo,string tname,string tspec,string remuNo)
{
InitializeComponent();
添加控件
rb[0] = rbcomputer;
rb[1] = rbphysics;
rb[2] = rbmath;
tspec = tspec.Trim();
foreach(RadioButton r in rb)
{
if ((r.Text).Equals(tspec))
r.Checked = true;
}
}
獲取checked的控件文本
string tspec="";
foreach(RadioButton c in rb)
{
if (c.Checked) tspec = c.Text;
}
CheckBox同理
補充一個 List<string>
合成爲String
List<string>
先轉成string[]數組
List<string> slist = new List<string>();
CheckBox[] checs = new CheckBox[3];
foreach(CheckBox c in checs)
if(c.checked) slist.Add(c.Text);
string res = string.Join(",",slist.ToArray());