Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value DataSource in ComboBox C#

Tags:

c#

combobox

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.

like image 761
Jonas452 Avatar asked Dec 16 '13 14:12

Jonas452


3 Answers

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." });
like image 146
DGibbs Avatar answered Oct 16 '22 22:10

DGibbs


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";
like image 38
Johan Nyman Avatar answered Oct 16 '22 22:10

Johan Nyman


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

like image 32
Steve Avatar answered Oct 16 '22 23:10

Steve