你的位置:首页 > ASP.net教程

[ASP.net教程]C#遍历得到checkboxlist选中值和设置选中项


得到选中项的value值并拼接成一个字符串返回

public string GetChecked(CheckBoxList checkList, string separator)
{
string str = "";
for (int i = 0; i < checkList.Items.Count; i++)
{
if (checkList.Items[i].Selected)
{
str += checkList.Items[i].Value + separator;
}
}
return str;
}

有选中字符串 分割之后遍历选中对应value值得选项

public void SetChecked(CheckBoxList checkList, string selval, string separator)
{
selval = separator + selval + separator; //例如:"0,1,1,2,1"->",0,1,1,2,1,"
for (int i = 0; i < checkList.Items.Count; i++)
{
checkList.Items[i].Selected = false;
string val = separator + checkList.Items[i].Value + separator;
if (selval.IndexOf(val) != -1)
{
checkList.Items[i].Selected = true;
selval = selval.Replace(val, separator); //然后从原来的值串中删除已经选中了的
if (selval == separator) //selval的最后一项也被选中的话,此时经过Replace后,只会剩下一个分隔符
{
selval += separator; //添加一个分隔符
}
}
}

}