當前位置:編程學習大全網 - 編程語言 - 編程題 4個CheckBox控件,文本中分別顯示C#程序設計、SQL Server、.NET Framework和ADO。NET,對四個Ch

編程題 4個CheckBox控件,文本中分別顯示C#程序設計、SQL Server、.NET Framework和ADO。NET,對四個Ch

//創建項目後,不需要拖拉控件,代碼動態創建控件事件

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?+?"被選中!");

}

}

}

  • 上一篇:中專有哪些專業適合男生
  • 下一篇:物理小故事
  • copyright 2024編程學習大全網