Reputation: 123
I have many class to set ComboBox datasource
- Position [DISPLAY, VALUE, ID, NAME]
- Division [DISPLAY, VALUE, ID, NAME]
- SubDivision [DISPLAY, VALUE, ID, NAME, DIVISIONID]
- ect.
and i binding data
List<Position> list = new List<Position>;
list.Add(...);
cboPosision.DataSource = list;
How to create method for ComboBox to insert row Null data
private void SetDataSource(this ComboBox cbo, object dataList, bool IncludeAll)
{
if(includeAll) { dataList.Add(null); } //Need Insert object {DISPLAY:"All", VALUE:null}
cbo.DataSource = dataList;
}
Upvotes: 0
Views: 259
Reputation: 82474
Here is one way to do it:
Create a common interface that all your combobox items must implement:
interface IComboBoxItem
{
string Display {get;set;}
object Value {get;set;
}
Then use a generic extension method to set that list as a data source:
private void SetDataSource<T>(this ComboBox cbo, IList<T> dataList, bool IncludeAll) where T : new, IComboBoxItem
{
if(includeAll)
{
dataList.Add(new T() {Display = "All", Value = null});
}
cbo.DisplayMember = "Display"; // This corresponds to the display member of the data object
cbo.ValueMember = "Value"; // this corresponds to the value member of the data object
cbo.DataSource = dataList;
}
Note: code written directly here, there might be some typos.
Upvotes: 1