We are binding a list of custom objects to an ASP.NET DropDownList in C# but we want to allow for the DropDownList to not have anything selected initially. One way of doing
Just working on this actually, here's what I got so far (along with a couple databinding goodies)
public interface ICanBindToObjectsKeyValuePair {
void BindToProperties(IEnumerable bindableEnumerable, Expression> textProperty, Expression> valueProperty);
}
public class EasyBinderDropDown : DropDownList, ICanBindToObjectsKeyValuePair {
public EasyBinderDropDown() {
base.AppendDataBoundItems = true;
}
public void BindToProperties(IEnumerable bindableEnumerable,
Expression> textProperty, Expression> valueProperty) {
if (ShowSelectionPrompt)
Items.Add(new ListItem(SelectionPromptText, SelectionPromptValue));
base.DataTextField = textProperty.MemberName();
base.DataValueField = valueProperty.MemberName();
base.DataSource = bindableEnumerable;
base.DataBind();
}
public bool ShowSelectionPrompt { get; set; }
public string SelectionPromptText { get; set; }
public string SelectionPromptValue { get; set; }
public virtual IEnumerable ListItems {
get { return Items.Cast(); }
}
}
Notice one thing that you can do is
dropDown.BindToProperties(myCustomers, c=>c.CustomerName, c=>c.Id);