如何添加函数以向组合框添加空值

时间:2017-05-10 16:02:48

标签: c# winforms

我有很多类来设置ComboBox数据源

- Position [DISPLAY, VALUE, ID, NAME]
- Division [DISPLAY, VALUE, ID, NAME]
- SubDivision [DISPLAY, VALUE, ID, NAME, DIVISIONID]
- ect.

和我绑定数据

 List<Position> list = new List<Position>;
 list.Add(...);
 cboPosision.DataSource = list;

如何为ComboBox创建插入行空数据的方法

 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;
 }

1 个答案:

答案 0 :(得分:1)

这是一种方法:
创建一个所有组合框项目必须实现的通用接口:

interface IComboBoxItem 
{
    string Display {get;set;}
    object Value {get;set;
}

然后使用通用扩展方法将该列表设置为数据源:

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;
}

注意:直接写在这里的代码,可能会有一些拼写错误。