2013-12-16 56 views
5

我有一个组合框,那就是我如何填写它的数据:默认值数据源

SectorCollection sectorCollection = sectorController.SearchAll(); 

comboSector.DataSource = null; 

comboSector.DataSource = sectorCollection; 
comboSector.DisplayMember = "titleSector"; 
comboSector.ValueMember = "idSector"; 

我想是设置前的数据,就像没有在ComboBox文本值。 就像“选择一个扇区”。所以用户可以知道他在选择什么。

+3

这是winform还是asp.net? – Steve

回答

3

如果您使用的是WinForm的组合框,那么你应该在代码这样的事情

sectorCollection.Insert(0, new Sector() {idSector=0, titleSector="Select a sector"}) 

comboSector.DataSource = sectorCollection; 
comboSector.DisplayMember = "titleSector"; 
comboSector.ValueMember = "idSector"; 

您需要添加选择提示作为被添加到一个新的Sector实例然后将集合绑定到您的组合框。当然这可能是一个问题,如果你使用集合用于其他目的的一部分组合显示

+0

这工作,谢谢。 – Jonas452

+0

+1接近我需要的帮助。 – ghostJago

+1

@ghostJago缺少完全有用的东西? – Steve

4

就在索引0后插入一个新的项目作为默认的DataBind()

comboSector.DataSource = sectorCollection; 
comboSector.DisplayMember = "titleSector"; 
comboSector.ValueMember = "idSector"; 
comboSector.DataBind(); 

comboSector.Items.Insert(0, "Select a Sector."); 

如果这是WinForms(你没有说),那么你会在索引0一个新的项目添加到sectorCollection在分配给组合框之前。所有其他代码保持不变:

sectorCollection.Insert(0, new Sector() { idSector = 0, titleSector = "Select a sector." }); 
+0

+1正确,简洁和广泛使用的解决方案。 – nestedloop

+0

但是在ComboBox中没有“DataBind”方法,我知道必须将数据绑定到组合框,以便可以更改它。但我该怎么做? – Jonas452

+0

这是winforms吗? – DGibbs

1

我认为,而不是添加一个虚拟物品,它总是在列表的顶部,只需将SelectedIndex设置为 - 1并添加您的文本:

comboBox1.SelectedIndex = -1; 
comboBox1.Text = "Select an item";