checkboxlist绑定数据方法

checkboxlist绑定数据方法

1.把数据绑定到CheckBoxList中

特别要注意加载顺序

protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                SqlConnection con = GetDBCon.GetCon();
                con.Open();
                SqlDataAdapter sda = new SqlDataAdapter("select * from admin", con);
                DataSet ds = new DataSet();
                sda.Fill(ds,"admin");
                this.CheckBoxList1.DataSource = ds.Tables[0];
                this.CheckBoxList1.DataTextField = "username";//绑定的字段名
                this.CheckBoxList1.DataValueField = "userid";//绑定的值
                this.CheckBoxList1.DataBind();
               
             
                
            }
        }

2.循环读取出来

protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.Lab2.Text = "";
            for (int i = 0; i < CheckBoxList1.Items.Count; i++)
            {
                if (this.CheckBoxList1.Items[i].Selected)
                {
                    this.Lab2.Text = this.Lab2.Text+CheckBoxList1.Items[i].Text+".";
                }
            }
        }

 

 

3.CheckBoxList取值
string strrighgs = "";
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
if (CheckBoxList1.Items[i].Selected == true)
{
strrighgs += CheckBoxList1.Items[i].Value+"|";
}
}

string str = "";
foreach (ListItem li in CheckBoxList1.Items)
{
if (li.Selected == true)
{
str += li.Value+";";
}
}

Response.Write(str);
Response.End();
CheckBoxList取值及勾选
string[] strtemp = strapp.Split('|');
foreach (string str in strtemp)
{
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
if (CheckBoxList1.Items[i].Value == str)
{
CheckBoxList1.Items[i].Selected = true;
}
}
}

 

转自:http://hi.baidu.com/fzavdwpekkbfknq/item/3f1bf11b7e80336971d5e8c4

posted @ 2012-10-08 18:59  惊奇的野鹤  阅读(456)  评论(0编辑  收藏  举报