How to show text in combobox when no item selected?

前端 未结 16 1358
太阳男子
太阳男子 2020-11-30 06:39

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 \"Pl

16条回答
  •  半阙折子戏
    2020-11-30 07:05

    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;
                }
            }
    

提交回复
热议问题