CheckBoxList应用案例
编程方式添加ListItem对象
UI设计视图
UI代码视图
<%@ PageLanguage="C#"AutoEventWireup="true"CodeFile="CheckBoxList.aspx.cs"Inherits="CheckBoxList"%>
<!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>
<asp:CheckBoxList ID="cblGener" runat="server" AutoPostBack="True" RepeatColumns="3"
OnInit="cblGener_Init" OnSelectedIndexChanged="cblGener_SelectedIndexChanged">
</asp:CheckBoxList></div>
</form>
</body>
</html>
UI服务器端代码视图
protected void cblGener_Init(objectsender, EventArgs e)
{
//創建要添加選項
string[]Gener ={ "賜福","平安", "順利" };
string[]Code ={ "cf", "pa", "sl"};
for (int i = 0; i < Gener.Length;i++ )
{
cblGener.Items.Add(new ListItem(Gener[i],Code[i]));
}
}
UI运行时图
从数据源方式添加
protected void cblGener_Init(objectsender, EventArgs e)
{
//創建要添加選項
string[]Gener ={ "賜福","平安", "順利" };
string[]Code ={ "cf", "pa", "sl"};
cblGener.DataSource = Gener;
cblGener.DataBind();
}
//通過數組
string[,] GenerArray ={ { "C#第一版", "10.10" }, { "C#第二版","20.20" }, { "C#第三版", "30.30" } };
for (int i = 0; i < Gener.Length; i++)
{
cblGener.Items.Add(new ListItem(GenerArray[i,0],GenerArray[i,1]));
}
获取选择的值
protected void cblGener_SelectedIndexChanged(object sender, EventArgse)
{
StringBuilder sb = new StringBuilder();
foreach(ListItem li incblGener.Items)
{
if(li.Selected== true)
{
sb.Append("<br/>"+li.Value+"---" +li.Text);
}
}
lblSelectedCheckBox.Text =sb.ToString();
}