Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

ReadOnly ComboBox

3.00/5 (14 votes)
23 Oct 2008CPOL1 min read 2   1.4K  
An extended ComboBox that adds a ReadOnly property to it.

Sample.JPG

Introduction

I decided to create a new combobox based on requests from the users of MSDN Windows Forms forum. It adds a new property to the regular ComboBox so it can be set to read-only, much like the regular TextBoxes.

Using the code

I made this code pretty straightforward so all you have to do is download the C# file enclosed in the ZIP file above and add it to your project. Build it, and the ExComboBox should be available on the Toolbox.

You can change the way the disabled button looks by commenting the ComboBoxRenderer line and uncommenting the commented portion of the code. You can set the color of the gradient that makes the button of the read-only mode by changing the colors of the LinearGradientBrush variable lgb on the OnPaint method:

C#
protected class DblPanel : Panel
{
    protected override void OnPaint(PaintEventArgs e)
    {
        if (this.Visible == true)
        {
            ComboBoxRenderer.DrawDropDownButton(e.Graphics, e.ClipRectangle, 
              System.Windows.Forms.VisualStyles.ComboBoxState.Disabled);
            /*Pen pen = new Pen(Color.DarkGray);
            Pen penBR = new Pen(Color.LightGray);
            Pen penArrow = new Pen(Color.LightGray);
            penArrow.Width = 2;
            penArrow.EndCap = LineCap.Square;
            Graphics g = e.Graphics;
            LinearGradientBrush lgb = new LinearGradientBrush(new Point(0, 0), 
                                      new Point(0, this.Height + 1), 
                                      Color.LightGray, Color.Gray);

Points of interest

I learned a bit while trying to add the read-only feature to the regular ComboBox. It is interesting that the combobox does not have any sub-controls in it (check the ComboBox.Controls.Count property and you will see it is 0); all is done by custom drawing. And, I also learned that there is no way to change this by overriding its Paint methods as it doesn't happen there; and, I couldn't figure out where it draws itself, so I used a Panel to draw over the regular dropdown button.

So basically, all the functionality is kept from the original combo box except the ability for the user to change the selected item without disabling the control (many complained that setting the Enabled property to false made it difficult to read and didn't allow the use of custom colors).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)