How to set multiple selected values in asp.net checkboxlist

倖福魔咒の 提交于 2019-12-04 01:18:37

I know this is an old post but I had the same problem recently.

To select multiple items of a DataBound CheckBoxList, handle the DataBound event and loop through the Items collection setting the Selected property individually on each item as required.

Setting the SelectedValue property of the control only checks the final item.

 foreach (ListItem item in MyCheckBoxList.Items)
 {
     item.Selected = ShouldItemBeSelectedMethod(item.Value);
 }

Nice method I use:

 private void SetCheckBoxListValues(CheckBoxList cbl, string[] values)
        {
            foreach (ListItem item in cbl.Items)
            {
                item.Selected = values.Contains(item.Value);
            }
        }
slnavn2000
public void SetValueCheckBoxList(CheckBoxList cbl, string sValues)
        {
            if (!string.IsNullOrEmpty(sValues))
            {                
                ArrayList values = StringToArrayList(sValues);             
                foreach (ListItem li in cbl.Items)
                {
                    if (values.Contains(li.Value))
                        li.Selected = true;
                    else
                        li.Selected = false;                    
                }               
            }
        }

private ArrayList StringToArrayList(string value)
        {
            ArrayList _al = new ArrayList();
            string[] _s = value.Split(new char[] { ',' });

            foreach (string item in _s)
                _al.Add(item);

            return _al;
        }

Thanks, slnavn2000

Cerebrus

Sounds like a Page Lifecycle - Databinding question.

You should really take a look at (the answers to) this question.

I used the DataBound event to select to set the selected items.

set checkboxlist selected items from a list:

        List<int> yourlist;
        //fill yourlist
        foreach (ListItem item in checkboxlist.Items)
        {
            if (yourlist.Contains(int.Parse(item.Value.ToString())))
                item.Selected = true;                
        }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!