博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

CheckBoxList 的数据绑定及数据获取

Posted on 2006-10-06 07:33  孤峰皓月  阅读(1510)  评论(0编辑  收藏  举报

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;
using System.Data.SqlClient;        //自己导入命名空间.
public partial class like : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack)    //这句很重要,如果不加,则每次加载时都要执行一次绑定,易丢失数据.
        {
        //创建链接;
        SqlConnection con = DB.createConnection();      //不再用 new
        con.Open();
        SqlCommand cmd = new SqlCommand("select * from [personlike]",con);
        SqlDataReader sdr = cmd.ExecuteReader();

        this.CheckBoxList1.DataTextField = "likeContent";  
        this.CheckBoxList1.DataValueField = "ID";

        this.CheckBoxList1.DataSource = sdr;
        this.CheckBoxList1.DataBind();

        sdr.Close();        //关闭记录集
        con.Close();        //关闭链接

        }
    }


//单击按钮读取所做的操作(数据),用Response.Write()方法显示.

    protected void Button1_Click(object sender, EventArgs e)
    {
        for(int i=0;i<=this.CheckBoxList1.Items.Count-1;i++)
        {
            if(this.CheckBoxList1.Items[i].Selected)
            {
                Response.Write(this.CheckBoxList1.Items[i].Value.ToString() +"-"+this.CheckBoxList1.Items[i].Text + "<br>");
            }
        }
    }
}