Clear Checkbox

Clear Checkbox

Controls featured in this example:

  • Sitecore Web Control

Classes featured in this example:

  • Sitecore.Configuration.Factory
  • Sitecore.Data.Database
  • Sitecore.Data.Fields.CheckboxField
  • Sitecore.Data.Items.Item
  • Sitecore.MainUtil
  • Sitecore.SecurityModel.SecurityDisabler

Clear Checkbox C# Web Control Code

Sitecore.Data.Database db = Sitecore.Configuration.Factory.GetDatabase("master");
Sitecore.Data.Items.Item item = db.GetItem("/sitecore/content/TIC-Meta/FieldsDemos/Simple Fields");
if (item == null) return;

output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-weight:bold; width:100%; clear:both");
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.Div);
output.Write("{0}", "C# Web Control Real-time Output");
output.RenderEndTag();

output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-size:x-small; width:100%; clear:both");
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.Div);
output.AddAttribute(System.Web.UI.HtmlTextWriterAttribute.Style, "font-weight:bold");
output.RenderBeginTag(System.Web.UI.HtmlTextWriterTag.P);
//using : for colon and   for space
output.Write("{0}: {1}", "Item", item.DisplayName);
output.RenderEndTag(); //P

using (new Sitecore.SecurityModel.SecurityDisabler())
{
    try
    {
        Sitecore.Data.Fields.CheckboxField checkbox = item.Fields["example checkbox"];
        if (checkbox != null) 
        {
if (checkbox.Checked)
{
    item.Editing.BeginEdit();
    checkbox.Checked = false;
    item.Editing.EndEdit();
}
string check = checkbox.Checked.ToString();
if (!string.IsNullOrEmpty(check))
{
   //display field value and add linebreak 
output.Write(checkbox.InnerField.DisplayName + " Field Value: <b>" + checkbox.Value + "</b><br/>"); 
if (checkbox.Checked) 
output.Write("Checkbox on Simple Fields page is checked"); 
else 
output.Write("Checkbox on Simple Fields page is not checked");}
        }
    }
    finally
    {
        output.RenderEndTag(); //Div
    }
}

Clear Checkbox C# Web Control Output

Example Checkbox Field Value: 0
Checkbox on Simple Fields page is not checked

Notes

  • A Checkbox field stores the value 1 when a user checks the checkbox
  • Check for a value of “1” to determine if the checkbox is checked