Search code examples
sharepoint-2010checkboxlistmultiple-choicechoicefield

How to Save Choice Field to Sharepoint List in a webpart?


I have a SharepointList

List Name:RegionList Fields: regId number Regname Choice(CheckBox: with Allow Multiple Selection)

The Choice field items are displayed in CheckBoxList items. I am saving these items as string with Comma Separated Values.

protected string GetSelectedRegions()
        {
            List<String> regList = new List<string>();
            // Loop through each item.
            foreach (ListItem item in chkRegion.Items)
            {
                if (item.Selected)
                {
                    // If the item is selected, add the value to the list.
                    regList.Add(item.Value);
                }
                else
                {
                    // Item is not selected, do something else.
                }
            }

            String regs = String.Join(",", regList.ToArray());
            return regs;
        }

From above code the regs parameter has number of selected items and saved to List. Now, Problem is when i open the list and open record in Edit Mode then CHOICE Field Doesn't Show any Selected ITEM. But, when i send only single value then it Show the Selected Item that was saved.

Any Idea? Plz let me know how to store the CheckBoxList items to CHOICE Field and Retrive it. Thanks in Advance!


Solution

  • for set multi-Checkbox you should use SPFieldMultiChoiceValue like this:

    protected SPFieldMultiChoiceValue GetSelectedRegions()
         {
            SPFieldMultiChoiceValue multiValue = new SPFieldMultiChoiceValue();
    
             List<String> regList = new List<string>();
            // Loop through each item.
            foreach (ListItem item in chkRegion.Items)
            {
                if (item.Selected)
                {
                    // If the item is selected, add the value to the list.
                    multiValue.Add(item.Value);
                }
                else
                {
                    // Item is not selected, do something else.
                }
            }
    
            //String regs = String.Join(",", regList.ToArray());
            return multiValue;
        }
    

    than set your SPFieldMultiChoiceValue to your SPListItem

      item["multivalued choice field name"]= GetSelectedRegions();