Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show text in combobox when no item selected?

C# & .Net 2.0 question (WinForms)

I have set of items in ComboBox and non of them selected. I would like to show a string on combo "Please select item" in that situation.

Current implementation is just added empty item with such text on index 0 and remove it when user select one of following items. Unfortunately empty item is shown in dropdown list as well. How to avoid this situation or in other way - is there any way to show custom text on ComboBox when no item is selected?

Answers below work when ComboBoxStyle is set to DropDown (ComboBox is editable). Is there possibility to do this when ComboBoxStyle is set to DropDownList?

like image 781
jotbek Avatar asked Nov 09 '11 11:11

jotbek


1 Answers

Use the insert method of the combobox to insert the "Please select item" in to 0 index,

comboBox1.Items.Insert(0, "Please select any value"); 

and add all the items to the combobox after the first index. In the form load set

comboBox1.SelectedIndex = 0; 

EDIT:

In form load write the text in to the comboBox1.Text by hardcoding

comboBox1.Text = "Please, select any value"; 

and in the TextChanged event of the comboBox1 write the following code

 private void comboBox1_TextChanged(object sender, EventArgs e)         {             if (comboBox1.SelectedIndex < 0)             {                 comboBox1.Text = "Please, select any value";             }             else             {                 comboBox1.Text = comboBox1.SelectedText;             }         } 
like image 110
Sai Kalyan Kumar Akshinthala Avatar answered Sep 25 '22 18:09

Sai Kalyan Kumar Akshinthala