Jun 12, 2012

Working With Boolean (Checkbox) List Fields

While it is rather straightforward to retreive a value from a text field in code, the checkbox is a little bit more tricky, being a boolean field. 

Using boolean (checkbox) field in a CAML query 

To retreive items from a list with a CAML query, you use the elements <Eq> or <Neq>, as in equals to (Eq) or is not equal to (Neq), value. In Checkbox fields there is no actual value string touse in the CAML equasion, but the Value element is needed to state that the value is boolean, and thus the equal to comparison is made against TRUE/FALSE, namely whether value is false or not:
  • unchecked = false --> to retreive unchecked items, use <Eq>
  • checked = true --> to retreive checked items, use <Neq>
So the following CAML would return all the items where the NotDisplayed field ("Do not display in webpart") is not checked.

<Where><Eq><FieldRef Name='NotDisplayed'/><Value Type='Boolean'></Value></Eq></Where>

Using boolean (checkbox) field in code, to retreive or set the value

In your code you might need to determine whether the checkbox of a list item (or any list item) is checked or not in order to do something, e.g.

bool YesOrNoValue= (bool)item["YesOrNoField"];
if (YesOrNoValue == true)
{
   ...do something
}
else
{
   ...do something
}

If you need to retrieve the value to use it as a string, you need a slightly different approach:

SPFieldBoolean YesOrNo = item.Fields["Item value is yes?"] as SPFieldBoolean;
bool YesOrNoValue= (bool)YesOrNo.GetFieldValue(item["YesOrNoField"].ToString());

To set the checkbox value, you can use a simple

item["YesOrNoField"] = true;
item.Update();

No comments: