using System; using System.Data; using System.Configuration; 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; //自己加的命名空间 /**////<summary> /// DB 的摘要说明 ///</summary> publicclass DB ...{ public DB() ...{ // // TODO: 在此处添加构造函数逻辑 // } publicstatic SqlConnection createConnection() //自己创建 ...{ //创建一个静态的数据库链接 System.Data.SqlClient.SqlConnection con =new SqlConnection("server=.;database=login;uid=sa;pwd=*********;"); return con; } }
使用SQL创建数据库和创建表(数据库名:login 表名:personlike),代码如下:
use login go create table personlike ( id int primary key, likecontent varchar(100) not null ) go insert into personlike values(1,'体育') insert into personlike values(2,'旅游') insert into personlike values(3,'足球') insert into personlike values(4,'篮球') insert into personlike values(5,'游泳')
双击CheckBoxList控件,响应控件事件,代码如下:
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; publicpartialclass like : System.Web.UI.Page ...{ protectedvoid Page_Load(object sender, EventArgs e) ...{ //自己添加的代码 SqlConnection con = DB.createConnection(); 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(); } protectedvoid CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e) ...{ } }