Asp.Net從零開始學-6
CheckBoxList繫結資料庫
資料庫連線累DB.CS
using System;
using System.Data.SqlClient;
namespace Test2_1
{
public class DB
{
public static SqlConnection createConnection(){
SqlConnection con=new SqlConnection("server=.;database=login;uid=sa;pwd=12345678");//資料連線
return con;
}
}
頁面
private void Page_Load(object sender, System.EventArgs e)
{
// 在此處放置使用者程式碼以初始化頁面
if(!this.IsPostBack){
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();
}
}
private void Button1_Click(object sender, System.EventArgs e)
{
for(int i=0;i<this.CheckBoxList1.Items.Count;i++)
{
if(this.CheckBoxList1.Items[i].Selected)
{
Response.Write(this.CheckBoxList1.Items[i].Value.ToString()+"-"+this.CheckBoxList1.Items[i].Text+"<br>");
}
}
}