Thursday, January 22, 2009 4:31 PM
While refactoring an application today, I had to configure a couple of ComboBoxes programmaticaly.
To simplify this, I cam up with the following piece of code.
public class ComboboxBinder
{
//---- Members -----------------------------------------------------
private readonly ComboBox _combobox;
//---------------------------------------------------------
private ComboboxBinder(ComboBox comboBox)
{
_combobox = comboBox;
}
//---------------------------------------------------------
public static ComboboxBinder Bind(ComboBox cbo)
{
return new ComboboxBinder(cbo);
}
//---------------------------------------------------------
public ComboboxBinder DataSource(object source)
{
_combobox.DataSource = source;
return this;
}
//---------------------------------------------------------
public ComboboxBinder ViewForDataSource(DataTable table)
{
return DataSource(new DataView(table));
}
//---------------------------------------------------------
public ComboboxBinder ViewForDataSource(DataTable table, string filter)
{
return ViewForDataSource(table, filter, "");
}
//---------------------------------------------------------
public ComboboxBinder ViewForDataSource(DataTable table, string filter, string sort)
{
var view = new DataView(table);
view.RowFilter = filter;
view.Sort = sort;
return DataSource(view);
}
//---------------------------------------------------------
public ComboboxBinder DisplayMember(string member)
{
_combobox.DisplayMember = member;
return this;
}
//---------------------------------------------------------
public ComboboxBinder ValueMember(string member)
{
_combobox.ValueMember = member;
return this;
}
//---------------------------------------------------------
public ComboboxBinder SelectedValue(object value)
{
_combobox.SelectedValue = value;
return this;
}
//---------------------------------------------------------
public ComboboxBinder SelectedIndex(int index)
{
_combobox.SelectedIndex = index;
return this;
}
}
It implements a fluent interface to setup the ComboBox with a little less noisy code:
ComboboxBinder.Bind(cboType)
.ViewForDataSource(_typeTable, "", "Name")
.DisplayMember("Name")
.ValueMember("TypeID")
.SelectedIndex(1);
ComboboxBinder.Bind(cboState)
.ViewForDataSource(_stateTable)
.DisplayMember("Description")
.ValueMember("StateID")
.SelectedIndex(1);
Hopefully its useful for someone. Of course you would probably have it change it to fit your needs.
nothing impossible
roboto