Working with SPFieldMultiChoiceValue: Saving and Loading

If you’re working with a column of type choice, and you’ve opted to allow multiple selections via checkboxes, the following article will hopefully help fill in the blanks. I will cover reading data from this type of column and populating an ASP.NET checkboxlist and saving data from an ASP.NET checkboxlist to this type of column.

Saving Data

Let’s say you have an ASP.NET control that you’ve defined on your page similar to:

1
2
3
4
5
<asp:CheckBoxList ID="cblMW" runat="server" RepeatDirection="Horizontal" Font-Size="11px">
                        <asp:ListItem Text="Option1" Value="Option1"></asp:ListItem>
                        <asp:ListItem Text="Option2" Value="Option2"></asp:ListItem>
                        <asp:ListItem Text="Option3" Value="Option3"></asp:ListItem>
</asp:CheckBoxList>

In order to save the items that are selected in this checkboxlist control to the SharePoint column, you can use the following piece of code:

1
2
3
4
5
6
7
8
9
10
11
SPFieldMultiChoiceValue itemValue = new SPFieldMultiChoiceValue();
 
// Iterate through the Items collection of the CheckBoxList 
// control and display the selected items.
for (int i = 0; i < cblMW.Items.Count; i++)
{
    if (cblMW.Items[i].Selected)
    {
        itemValue.Add(cblMW.Items[i].Text);
    }
}

Loading Data

Finally, you may need to retrieve data stored in a choice column and load it into a checkboxlist. Here’s how you do that:

1
2
3
4
5
6
SPFieldMultiChoiceValue multiChoice = new SPFieldMultiChoiceValue(Convert.ToString(listItem["FieldName"]));           
 
for (int i = 0; i < multiChoice.Count; i++)
{
    cblMW.Items.FindByText(multiChoice[i]).Selected = true;
}

2 Responses to “Working with SPFieldMultiChoiceValue: Saving and Loading”

  1. subhishine December 2, 2012 at 1:24 am #

    I’ve already followed your instructions, but I have a problem.
    The situation is:
    I have 7 multiple choices. I’ve checked all choices (1-7) & click save.
    The result is only choices number 1,3,5, and 7 saved.
    What’s wrong?..

    thank u for ur attention & sorry for my bad english.

  2. shereen December 4, 2012 at 1:48 pm #

    Are items 2,4 and 6 being added after the fact? Can you post some code so we can see what’s happening?

Leave a Reply