//创建一个个人爱好选择模块
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("server=WEQWERWER\\SQLEXPRESS;database=TestDataBase;uid=sa;pwd=zj.");
conn.Open();
SqlCommand cmd = new SqlCommand("select * from PersonLike", conn);
SqlDataReader sdr = cmd.ExecuteReader();
//int i = 0;
//while (sdr.Read()) //只有Read()后,才可以sdr.GetString(1)
//{
// this.CheckBoxList1.Items.Add(" ");//此段代码很重要,首先添加一行,为下面代码赋值做准备
// this.CheckBoxList1.Items[i].Text = sdr.GetString(1);
// this.CheckBoxList1.Items[i].Selected = sdr.GetBoolean(2);
// i++;
//}
//另一种实现方法,不过现在还无法把选中状态从数据库中提取出来,此方法为常用方法
this.CheckBoxList1.DataSource = sdr; //数据源绑定
//Response.Write( this.CheckBoxList1.Items.Count); //此时无法获得CheckBoxList的记录数
CheckBoxList1.DataTextField = "PLike";
CheckBoxList1.DataValueField = "YN"; //值为True 或false
CheckBoxList1.DataBind();//此段代码必须
for (i=0; i < this.CheckBoxList1.Items.Count; i++)
{
if (CheckBoxList1.Items[i].Value == "True")
{
CheckBoxList1.Items[i].Selected = true;
}
else
{
CheckBoxList1.Items[i].Selected = false;
}
}
sdr.Close();
conn.Close();
}
//Sql
create database TestDataBase
use TestDataBase
create table PersonLike
( id int primary key,
Plike varchar(100) not null,
YN bit not null default 0
)
insert into PersonLike values(1,'钓鱼',default)
insert into PersonLike values(2,'足球',default)
insert into PersonLike values(3,'篮球',default)