CheckBoxList的得值和賦值!!!!!!

來源:互聯網
上載者:User
 

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;
        }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.