Default value DataSource in ComboBox C#

跟風遠走 提交于 2019-12-23 10:07:08

问题


I have a ComboBox, and that is how I fill the data in it:

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.


回答1:


If you are using a WinForm combobox then you should code something like this

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. Of course this could be a problem if you use the collection for other purposes a part from the combo display




回答2:


Just insert a new item at index 0 as the default after your 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. All other code remains the same:

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



回答3:


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:

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


来源:https://stackoverflow.com/questions/20613885/default-value-datasource-in-combobox-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!