5

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.

Jonas452
  • 420
  • 6
  • 19

3 Answers3

4

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." });
DGibbs
  • 14,316
  • 7
  • 44
  • 83
  • But there is no method "DataBind" in a ComboBox, I understood that I have to Bind the Data into the combobox so I can change it. But how can I do that? – Jonas452 Dec 16 '13 at 15:20
  • 1
    Downvoter, please leave a comment explaining how this answer can be improved. – DGibbs Dec 19 '13 at 09:23
4

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";
Johan Nyman
  • 268
  • 3
  • 9
3

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

Steve
  • 213,761
  • 22
  • 232
  • 286