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;
}
}
}
<asp:CheckBoxList ID="cblproject" name="cblproject" runat="server" RepeatDirection="Horizontal" RepeatLayout="Flow">
</asp:CheckBoxList>
//绑定项目数据
BLL.project bll_prjct = new BLL.project();
DataSet ds_prjct = bll_prjct.GetList(50, " “,"id desc");
cblproject.DataSource = ds_prjct.Tables[0];
cblproject.DataValueField = "id";
cblproject.DataTextField = "project_name";
cblproject.DataBind();
//添加方法中,修改方法中也一样
string project_id = "";
for (int i = 0; i < cblproject.Items.Count; i++)
{
if (cblproject.Items[i].Selected == true) project_id +=cblproject.Items[i].Value + "|";
}
model.project_id = project_id;
//修改时加载数据,DelLastChar为去掉最后一个字符的方法,model.project_id的结构为6|7|4|
string[] project_list = DelLastChar(model.project_id, "|").Split('|');
foreach(string str in project_list)
{
for (int i = 0; i < cblproject.Items.Count; i++)
{
if (cblproject.Items[i].Value == str)
{
cblproject.Items[i].Selected = true;
}
}
}