How to show text in combobox when no item selected?

前端 未结 16 1344
太阳男子
太阳男子 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

    I used a quick work around so I could keep the DropDownList style.

    class DummyComboBoxItem
    {
        public string DisplayName
        {
            get
            {
                return "Make a selection ...";
            }
        }
    }
    public partial class mainForm : Form
    {
        private DummyComboBoxItem placeholder = new DummyComboBoxItem();
        public mainForm()
        {
            InitializeComponent();
    
            myComboBox.DisplayMember = "DisplayName";            
            myComboBox.Items.Add(placeholder);
            foreach(object o in Objects)
            {
                myComboBox.Items.Add(o);
            }
            myComboBox.SelectedItem = placeholder;
        }
    
        private void myComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (myComboBox.SelectedItem == null) return;
            if (myComboBox.SelectedItem == placeholder) return;            
            /*
                do your stuff
            */
            myComboBox.Items.Add(placeholder);
            myComboBox.SelectedItem = placeholder;
        }
    
        private void myComboBox_DropDown(object sender, EventArgs e)
        {
            myComboBox.Items.Remove(placeholder);
        }
    
        private void myComboBox_Leave(object sender, EventArgs e)
        {
            //this covers user aborting the selection (by clicking away or choosing the system null drop down option)
            //The control may not immedietly change, but if the user clicks anywhere else it will reset
            if(myComboBox.SelectedItem != placeholder)
            {
                if(!myComboBox.Items.Contains(placeholder)) myComboBox.Items.Add(placeholder);
                myComboBox.SelectedItem = placeholder;
            }            
        }       
    }
    

    If you use databinding you'll have to create a dummy version of the type you're bound to - just make sure you remove it before any persistence logic.

提交回复
热议问题