using?System;
using?System.Collections.Generic;
using?System.Drawing;
using?System.Windows.Forms;
namespace?Test
{
public?partial?class?MainForm?:?Form
{
public?MainForm()
{
InitializeComponent();
}
void?MainFormLoad(object?sender,?System.EventArgs?e)
{
this.Size?=?new?Size(400,?250);//設置窗體大小
string[]?text?=?new?string[]{"C#程序設計",?"SQL?Server",?".NET?Framework",?"ADO.NET"};//控件名稱數組
try
{
//動態添加四個CheckBox控件
for?(int?i?=?0;?i?<?4;?i++)
{
CheckBox?cb?=?new?CheckBox();
cb.AutoSize?=?true;
if?(i?<?2)
{
cb.Top?=?50;
cb.Left?=?50?+?i?*?200;
}
else
{
cb.Top?=?100;
cb.Left?=?50?+?(i?-?2)?*?200;
}
cb.Text?=?text[i];
this.Controls.Add(cb);
}
//動態添加壹個Button控件和事件
Button?btn?=?new?Button();
btn.Top?=?150;
btn.Left?=?150;
btn.Text?=?"確定";
this.Controls.Add(btn);
btn.Click?+=?new?System.EventHandler(btnClick);
}?catch?(Exception)?{
throw;
}
}
void?btnClick(object?sender,?System.EventArgs?e)
{
List<string>?strs?=?new?List<string>();//存儲選中項的泛型集合
foreach?(Control?control?in?this.Controls)//遍歷窗體上所有控件
{
if?(control?is?CheckBox)//判斷CheckBox控件
{
if?(((CheckBox)control).Checked?==?true)
{
strs.Add(control.Text);
}
}
}
if?(strs.Count?==?0)
{
MessageBox.Show("未選中任何科目!");
return;
}
string?result?=?string.Empty;
for?(int?i?=?0;?i?<?strs.Count;?i++)
{
if?(strs.Count?==?1)//只選中壹項
{
result?=?strs[0];
break;
}
else?if?(i?<?strs.Count?-?1)
{
result?+=?strs[i]?+?"、";//多選的中間項要在後面加上頓號
}
else
{
result?+=?strs[i];//多選的最後壹項
}
}
MessageBox.Show(result?+?"被選中!");
}
}
}