Where this is code that is duplicated all over the place with only minor alterations for the data source and the default value:
DropDownList cbo = new DropDownList();
cbo.DataSource = PersonMotherObject.GetPersons();
cbo.DataTextField = "FirstName";
cbo.DataValueField = "LastCommaFirst";
cbo.DataBind();
cbo.Items.Insert(0, new ListItem("", "----- SELECT -----"));
foreach (ListItem listItem in cbo.Items)
{
listItem.Selected = listItem.Value == "Flanders, Ned";
}
This reads a lot easier, and gets us a little more DRY:
new ComboBoxSetter<Person>()
.WithListControl(ddl)
.WithDataSourceOf(PersonMotherObject.GetPersons())
.SetSelectedWhereTextIs("Ned")
.AddLeadingItemOf("", "-----Select------")
.TheDataTextFieldIs("FirstName")
.TheDataValueFieldIs("LastCommaFirst")
.Bind();
The class that does the grunt work (reformatted for brevity)
/// <summary>
/// Provides a fluent interface for setting a combo box
/// </summary>
public class ComboBoxSetter<T>
{
private ListControl Control;
private IList<T> DataSource;
private string DefaultValue;
private ListItem ListItemToAdd;
private string DataValueField;
private string DataTextField;
public void Bind()
{
Control.DataSource = DataSource;
Control.DataTextField = DataTextField;
Control.DataValueField = DataValueField;
Control.DataBind();
if (ListItemToAdd != null)
Control.Items.Insert(0, ListItemToAdd);
if (!string.IsNullOrEmpty(DefaultValue))
foreach (ListItem listItem in Control.Items)
listItem.Selected = listItem.Text == DefaultValue;
}
public ComboBoxSetter<T> WithListControl(ListControl ddl)
{
Control = ddl;
return this;
}
public ComboBoxSetter<T> WithDataSourceOf(IList<T> people)
{
DataSource = people;
return this;
}
public ComboBoxSetter<T> SetSelectedWhereTextIs(string defaultSelection)
{
DefaultValue = defaultSelection;
return this;
}
public ComboBoxSetter<T> AddLeadingItemOf(string value, string display)
{
ListItemToAdd = new ListItem(display, value);
return this;
}
public ComboBoxSetter<T> AddLeadingItemOf(ListItem leadingItem)
{
ListItemToAdd = leadingItem;
return this;
}
public ComboBoxSetter<T> TheDataValueFieldIs(string dataValueField)
{
DataValueField = dataValueField;
return this;
}
public ComboBoxSetter<T> TheDataTextFieldIs(string dataTextField)
{
DataTextField = dataTextField;
return this;
}