How to make Combobox in winforms readonly

后端 未结 18 2062
攒了一身酷
攒了一身酷 2020-12-08 09:40

I do not want the user to be able to change the value displayed in the combobox. I have been using Enabled = false but it grays out the text, so it is not very

18条回答
  •  眼角桃花
    2020-12-08 10:06

    I've handled it by subclassing the ComboBox to add a ReadOnly property that hides itself when set and displays a ReadOnly TextBox on top containing the same Text:

    class ComboBoxReadOnly : ComboBox
    {
        public ComboBoxReadOnly()
        {
            textBox = new TextBox();
            textBox.ReadOnly = true;
            textBox.Visible = false;
        }
    
        private TextBox textBox;
    
        private bool readOnly = false;
    
        public bool ReadOnly
        {
            get { return readOnly; }
            set
            {
                readOnly = value;
    
                if (readOnly)
                {
                    this.Visible = false;
                    textBox.Text = this.Text;
                    textBox.Location = this.Location;
                    textBox.Size = this.Size;
                    textBox.Visible = true;
    
                    if (textBox.Parent == null)
                        this.Parent.Controls.Add(textBox);
                }
                else
                {
                    this.Visible = true;
                    this.textBox.Visible = false;
                }
            }
        }
    }
    

提交回复
热议问题