页面代码: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="checkBoxANDCheckBoxList.aspx.cs" Inherits="checkBoxANDCheckBoxList" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>无标题页</title> </head> <body> <form id="form1" runat="server"> <div> CheckBoxList控件演示程序<br /> <br /> 请选择你喜欢的计算机语言类型<br /> <asp:CheckBoxList ID="CheckBoxList1" runat="server" RepeatDirection="Horizontal"> <asp:ListItem>Visual Basic</asp:ListItem> <asp:ListItem>C#</asp:ListItem> <asp:ListItem>C++</asp:ListItem> <asp:ListItem>Jscript</asp:ListItem> <asp:ListItem>XAML</asp:ListItem> <asp:ListItem>Java</asp:ListItem> </asp:CheckBoxList></div> <br /> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="确定" /><br /> <asp:CheckBox ID="CheckBox1" runat="server" AutoPostBack="True" OnCheckedChanged="CheckBox1_CheckedChanged" Text="改变显示风格" /> <asp:CheckBox ID="CheckBox2" runat="server" AutoPostBack="True" OnCheckedChanged="CheckBox2_CheckedChanged" Text="改变字体颜色" /><br /> <br /> 你选择的计算机语言类型为:<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> </form> </body> </html> 后台代码: using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class checkBoxANDCheckBoxList : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void CheckBox1_CheckedChanged(object sender, EventArgs e) { //改变背景颜色 this.CheckBoxList1.BackColor = CheckBox1.Checked ? System.Drawing.Color.Red : System.Drawing.Color.Purple; //改变样式(水平和垂直) CheckBoxList1.RepeatDirection = CheckBox1.Checked ? RepeatDirection.Vertical : RepeatDirection.Horizontal; } protected void CheckBox2_CheckedChanged(object sender, EventArgs e) { //改变字体颜色 CheckBoxList1.ForeColor = CheckBox2.Checked ? System.Drawing.Color.PowderBlue : System.Drawing.Color.RoyalBlue; Label1.ForeColor = CheckBox2.Checked ? System.Drawing.Color.SandyBrown : System.Drawing.Color.Tomato; } protected void Button1_Click(object sender, EventArgs e) { string str = ""; Label1.Text = ""; for (int i = 0; i < CheckBoxList1 .Items .Count ; i++) { if (CheckBoxList1 .Items [i].Selected )//遍历checkboxlist集合 { str += CheckBoxList1.Items[i].Text + "*"; } } if (str.EndsWith ("*")==true)//字符串结尾比较 { str = str.Substring(0, str.Length - 1); } if (str=="") { //添加javascript验证 string scriptString = "alert('请作出选择')"; Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "warning", scriptString, true); } else { Label1.Visible = true; Label1.Text = str; } } }