设置或者得到CheckBoxList选中了的值

1.收集时,将CheckBoxList里选中的项转换成字符串,并用“,”隔开
这里只要调用方法GetChecked(CheckBoxList checkList, string separator)
就可以获取到想要的数据。然后存入数据库。

2.显示时,先从库里获取爱好的数据(刚刚用“,”隔开的字符串),
 然后调用方法SetChecked(CheckBoxList checkList,string selval,string separator)
就可以将库里的数据用CheckBoxList的形式表现出来

......
方法的使用:
//这里获取CheckBoxList中的选中项并用","隔开
string str=GetChecked(this.checkList1, ",");
......
//这里是将str这个字符串的值又设回CheckBoxList
SetChecked(this.checkList1,str,",");

        /// <summary>
        /// 初始化CheckBoxList中哪些是选中了的         /// </summary>
        /// <param name="checkList">CheckBoxList</param>
        /// <param name="selval">选中了的值串例如:"0,1,1,2,1"</param>
        /// <param name="separator">值串中使用的分割符例如"0,1,1,2,1"中的逗号</param>
        public static string 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;        //添加一个分隔符
                    }
                }
            }
            selval = selval.Substring(1,selval.Length-2);        //除去前后加的分割符号
            return selval;
        }

        /// <summary>
        /// 得到CheckBoxList中选中了的值
        /// </summary>
        /// <param name="checkList">CheckBoxList</param>
        /// <param name="separator">分割符号</param>
        /// <returns></returns>
        public static string GetChecked(CheckBoxList checkList, string separator)
        {
            string selval = "";
            for(int i=0;i<checkList.Items.Count;i++)
            {
                if(checkList.Items[i].Selected)
                {
                    selval += checkList.Items[i].Value + separator;
                }
            }
            return selval;
        }

你可能感兴趣的:(checkbox)