Set hint or watermark or default text for ComboBox without adding it as item

前端 未结 3 1629
离开以前
离开以前 2020-12-04 03:46

So, I\'m trying to put some text showing up on the ComboBox before it has a selection made by the user.

That text should not be an item, selectable by t

3条回答
  •  旧时难觅i
    2020-12-04 03:54

    Ahh, dropdownlist. That ignores the .Text property by only allowing it to be set from an item in the items list.

    However. You can manipulate that list I guess by handling the addition and removal of an item so that it's not seen in the dropdown

        private void Form1_Load(object sender, EventArgs e)
        {
            //add an item to the combobox at the top
                comboBox1.Items.Insert(0, "Please select an item");
            //set the text
                comboBox1.Text = "Please select an item";
        }
    
        private void comboBox1_DropDown(object sender, EventArgs e)
        {
            //when we click to open the dropdown, we remove that item
            if (comboBox1.Items.Contains("Please select an item"))
                comboBox1.Items.RemoveAt(0);
        }
    
        private void comboBox1_DropDownClosed(object sender, EventArgs e)
        {
            //when we close the dropdown, if we select an item the dropdown
            //displays that item, if now we set back to our text.
            if (comboBox1.SelectedIndex == -1)
            {
                comboBox1.Items.Insert(0, "Please select an item");
                comboBox1.Text = "Please select an item";
    
            }
    
        }
    

    and depending on if your code would reset the form without a form_load being called, you would probably need something in the SelectedIndexchanged event to cover if you somewhere set the combobox's selectedindex back to -1 as this code wouldn't cover that.

提交回复
热议问题