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.
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." });
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";
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With