Asp.Net从零开始学-6

    技术2022-05-11  20

                        CheckBoxList绑定数据库

    数据库连接累DB.CSusing 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>");    }   }  }


    最新回复(0)