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值判断是否存在与选中项字符串中

选中对应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;//得到value值并加工便于匹配
if (selval.IndexOf(val) != -1)//判断是否存在 不等于-1表示存在
{
checkList.Items[i].Selected = true; //使该项处于选中状态
selval = selval.Replace(val, separator); //然后从原来的值串中删除已经选中了的
if (selval == separator) //selval的最后一项也被选中的话,此时经过Replace后,只会剩下一个分隔符
{
break;
}
}
}

}