1.利用foreach对页面控件的遍历 及三目运算符的使用
利用div将一组CheckBox放在一起用于遍历
<body>
<form id="form1" runat="server">
<div>
<asp:CheckBox ID="cb_1" runat="server" AutoPostBack="true" Text="我是自动的"
oncheckedchanged="cb_1_CheckedChanged" />
<asp:TextBox ID="tb_1" runat="server"></asp:TextBox> <br />
<br />
<br />
<div id="chklist" runat="server">
<asp:CheckBox ID="cb_2" runat="server" Text="看书" />
<asp:CheckBox ID="cb_3" runat="server" Text="听歌" />
<asp:CheckBox ID="cb_4" runat="server" Text="旅游" />
<asp:CheckBox ID="cb_5" runat="server" Text="跳舞" /> <br /> <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /><br />
<asp:TextBox ID="tb_2" runat="server" TextMode="MultiLine" Width="300px" Height="300px"></asp:TextBox>
</div>
</div>
</form>
</body>
protected void Page_Load(object sender, EventArgs e)
{ } protected void cb_1_CheckedChanged(object sender, EventArgs e)
{
tb_1.Text = (cb_1.Checked) ? "被选中":"不被选中"; //三目运算符判断是否被使用
} protected void Button1_Click(object sender, EventArgs e)
{
tb_2.Text=" ";//显示前先清空
CheckBox _chk;
foreach(Control ctl in chklist.Controls) //chklist 为div Control 为CheckBox等的父类
{
if(ctl is CheckBox) //排除其它控件,确定是CheckBox
{
_chk=(CheckBox)ctl; //类型转换
if (_chk.Checked == true)
{
tb_2.Text += _chk.Text + ",";
}
}
}
}