Custom property – DropDown

Made my first customized property today, and because I loved it so much in 4.6, the ice breaker was a DropDown property that takes values from the help-text.

Values in help text can be typed in two ways:
“Shown text:value” or just “value” eg. “value1;Shown text:value2”

[Serializable]
[PageDefinitionTypePlugIn]
class PropertyDropDown : EPiServer.Core.PropertyString
{

public override EPiServer.Core.PropertyData ParseToObject(string value)
{
PropertyDropDown prop = new PropertyDropDown();
prop.String = value;
return prop;
}

public override EPiServer.Core.IPropertyControl CreatePropertyControl()
{
// Create an instance of MyCustomPropertyControl that is used
// for displaying the property.
return new PropertyDropDownControl();
}
}

class PropertyDropDownControl : EPiServer.Web.PropertyControls.PropertyDataControl
{
DropDownList dd;

public PropertyDropDown PropertyDropDown
{
get
{
return PropertyData as PropertyDropDown;

}
}

public override void CreateEditControls()
{
dd = new DropDownList();
this.ApplyControlAttributes(this.dd);
Controls.Add(dd);
this.SetupEditControls();
}

public override void CreateOnPageEditControls()
{
dd = new DropDownList();
this.ApplyControlAttributes(this.dd);
Controls.Add(dd);
this.SetupEditControls();
}

protected override void SetupEditControls()
{
dd.Items.Clear();
string[] values = PropertyDropDown.TranslateDescription().Split(';');
foreach (string value in values)
{
ListItem li = new ListItem();
if (value.Contains(":"))
{
li.Text = value.Split(':')[0];
li.Value = value.Split(':')[1];
}
else
{
li.Text = value;
li.Value = value;
}

li.Selected = li.Value.Equals(PropertyDropDown.Value);
dd.Items.Add(li);
}

if (dd.Items.Count == 0)
dd.Items.Add(new ListItem("No values found", ""));
}

public override void ApplyEditChanges()
{
base.SetValue(this.dd.SelectedValue);
}

public override void ApplyOnPageEditChanges()
{
base.SetValue(this.dd.SelectedValue);
}
}
}

5,795 thoughts on “Custom property – DropDown

  1. Joseph

    It is was very useful. I created the same for a Listbox control. Thanks a lot. Joseph

  2. Luis Rizo

    Thanx Erik. Very useful post. I was looking for a way to save the selected value which you provided. Thank you 🙂

Comments are closed.