CheckBoxList 控件比CheckBox要好用,我就不说为什么了,开玩笑说是因为 CheckBoxList比CheckBox多几个字母。嘻嘻。正经规范的话我不会说。我要做的就是利用数据绑定来做一个CheckBoxList例子。^_^
一。先托一个CheckBoxList 控件在页面。
二。创建数据库dingying 然后创建表:
Create table film
( id int primary key,
zhonglei varchar(100) not null
)
insert into film values(1,'恐怖片')
insert into film values(2,'动作片')
insert into film values (3,'犯罪片')//这是数据表创建代码,我也是刚开始学的。比你还菜呢?
就是这个表了,是看你喜欢看什么电影了,我是电影迷,爱看犯罪片。不知道你喜欢看什么片???
三。后台创建一个类db.cs
public static SqlDataReader Getdatareader(string sql )
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dianyingConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand(sql , con);
return ( cmd.ExecuteReader());
}
四。总算来到了.aspx.cs上了。
public partial class checkboxlist : System.Web.UI.Page
{
public SqlDataReader dr;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
dr = db.Getdatareader("select * from film");
CheckBoxList2.DataTextField = "zhonglei";
CheckBoxList2.DataValueField = "id";
CheckBoxList2.DataSource = dr;
CheckBoxList2.DataBind();
}
protected void Button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < CheckBoxList2.Items.Count; i++)
if (CheckBoxList2.Items[i].Selected)
{
Response.Write(CheckBoxList2 .Items [i].Value +"-"+CheckBoxList2 .Items [i].Text +"<br>");
}
}
好了,应该没问题吧!都懂吧!看看结果吧!