For this demo, we'll be using a very simple business object:

And a factory class to build our business objects:

Noisy Example:
What we sometimes run across in the UI code-behind is something that looks like this:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
IEnumerable<BizObject> source = BizObjectFactory.GetAll();
myCheckBox.DataSource = source;
myCheckBox.DataTextField = "Value";
myCheckBox.DataValueField = "Key";
myCheckBox.DataBind();
myDropDown.DataSource = source;
myDropDown.DataTextField = "Value";
myDropDown.DataValueField = "Key";
myDropDown.DataBind();
myBulletedList.DataSource = source;
myBulletedList.DataTextField = "Value";
myBulletedList.DataValueField = "Key";
myBulletedList.DataBind();
myListBox.DataSource = source;
myListBox.DataTextField = "Value";
myListBox.DataValueField = "Key";
myListBox.DataBind();
myRadioButtonList.DataSource = source;
myRadioButtonList.DataTextField = "Value";
myRadioButtonList.DataValueField = "Key";
myRadioButtonList.DataBind();
}
}
}
The thing that we should be screaming right about now is "Gadzooks! Look at all the repetition!". Most likely all the other pages with binding in the project will look similar to this one so it'll be a lot of code to look through when something has to change.
Solution 1:
In order to keep things more concise and manageable, what we should do is separate out the responsibility for binding to a simple generic helper class as follows.
public static class Binder
{
public static void Bind<T>(ListControl target, IEnumerable<T> source, String dataTextField, String dataValueField)
{
target.DataSource = source;
target.DataTextField = dataTextField;
target.DataValueField = dataValueField;
target.DataBind();
}
}
Since we have coded our helper class to the base ListControl class and the interface (IEnumerable<T>) we can use this same code for binding almost any type of collection with all the following objects.
Join the conversation! Your thoughts help the community grow.