简体   繁体   English

ComboBox C#中的默认值DataSource

[英]Default value DataSource in ComboBox C#

I have a ComboBox, and that is how I fill the data in it: 我有一个ComboBox,这就是我填充数据的方式:

SectorCollection sectorCollection = sectorController.SearchAll();

comboSector.DataSource = null;

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

What I want is to set a pre data, like a text in the combobox without a value. 我想要的是设置一个预数据,就像组合框中没有值的文本一样。 Like "Select a Sector." 比如“选择一个部门”。 So the user can knows what does he is selecting. 因此用户可以知道他正在选择什么。

Just insert a new item at index 0 as the default after your DataBind() : 只需在索引0处插入一个新项目作为DataBind()之后的默认值:

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

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

If this is WinForms (you haven't said) then you would add a new item to the sectorCollection at index 0 before assigning to the combobox. 如果这是WinForms (您还没有说过),那么在分配到组合框之前,您将在索引0处向sectorCollection添加一个新项目。 All other code remains the same: 所有其他代码保持不变:

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

If you are using a WinForm combobox then you should code something like this 如果您使用的是WinForm组合框,那么您应该编写类似这样的代码

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

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

You need to add the selection prompt as a new Sector instance added to the collection and then bind the collection to your combobox. 您需要将选择提示添加为添加到集合中的新Sector实例,然后将集合绑定到组合框。 Of course this could be a problem if you use the collection for other purposes a part from the combo display 当然,如果您将该集合用于组合显示中的其他部分,则可能会出现问题

I think rather than adding a dummy item, which will alway be on the top of the list, just set SelectedIndex to -1 and add your text: 我想,而不是添加一个虚拟项目,它总是在列表的顶部,只需将SelectedIndex设置为-1并添加您的文本:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM