Wednesday, February 16, 2011

How to select multiple value of a checkboxlist in C#?

Here I am showing how to select multiple value of a checkboxlist.
The SetValueCheckBoxList methode doing this where the StringToArrayList methode return the arrylist for the sValues parameter of SetValueCheckBoxList
    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;
                    li.Selected = false;

    private ArrayList StringToArrayList(string value)
        ArrayList _al = new ArrayList();
        string[] _s = value.Split(new char[] { ',' });
        foreach (string item in _s)
        return _al;
Call like this bellow
SetValueCheckBoxList(chkTypeHome, Convert.ToString(dtProperty.Rows[0]["TypeOfhome"]));
here chkTypeHome= checkboxlist
and Convert.ToString(dtProperty.Rows[0]["TypeOfhome"]) has data with comma separated sting like "1,2,4,5"