Click here to Skip to main content
12,751,306 members (34,723 online)
Click here to Skip to main content
Add your own
alternative version


146 bookmarked
Posted 6 Feb 2005

PropertyGrid and Drop Down properties

, 7 Feb 2005
Rate this:
Please Sign up or sign in to vote.
This article discusses three types of drop down properties.

Sample Image - DropDownProperties.jpg


This article discusses three types of drop down properties:

  1. Dynamic Enumeration - View a drop down combo box with dynamic values.
  2. Images & Text - Show different bitmaps based on the value in the drop down list.
  3. Drop Down Editor - Show a custom UI type editor as a drop down form.

Dynamic Enumeration

Often, we would like to show dynamic values in a combo box, avoiding hard coded values. Instead, we may load them from a database or text files to support globalization and more. In this case, the property is called Rule, and rules are loaded from the RichTextBox. First, we define an internal class, having a string array containing the list of values.

internal class HE_GlobalVars
    internal static string[] _ListofRules;

We also define a type converter as follows:

public class RuleConverter : StringConverter
    public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
        //true means show a combobox
        return true;

    public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
        //true will limit to list. false will show the list, 
        //but allow free-form entry
        return true;

    public override System.ComponentModel.TypeConverter.StandardValuesCollection 
           GetStandardValues(ITypeDescriptorContext context)
        return new StandardValuesCollection(HE_GlobalVars._ListofRules);

The Rule property is defined as follows:

public string Rule

    //When first loaded set property with the first item in the rule list.
    get {
        string S = "";
        if (_Rule != null)
            S = _Rule;
            if (HE_GlobalVars._ListofRules.Length > 0)
                //Sort the list before displaying it
                S = HE_GlobalVars._ListofRules[0];
        return S;
    set{ _Rule = value; }

Then, from the application itself, we fill the list of rules:

private void UpdateListofRules()
    int _NumofRules = richTextBox1.Lines.Length;
    HE_GlobalVars._ListofRules = new string[_NumofRules];
    for(int i = 0; i <= _NumofRules - 1; i++)
        HE_GlobalVars._ListofRules[i] = richTextBox1.Lines[i];

Images & Text

Some property types such as Image, Color, or Font.Name paint a small representation of the value just to the left of the space where the value is shown. This is accomplished by implementing the UITypeEditor PaintValue method. When the property browser renders a property value for a property that defines an editor, it presents the editor with a rectangle and a Graphics object with which to paint.

Here the property named SourceType is shown as a drop down list where each value has its own image located next to it. Images are loaded from a resource file.

public enum HE_SourceType {LAN, WebPage, FTP, eMail, OCR}

public class SourceTypePropertyGridEditor : UITypeEditor
    public override bool GetPaintValueSupported(ITypeDescriptorContext context)
        //Set to true to implement the PaintValue method
        return true;

    public override void PaintValue(PaintValueEventArgs e)
        //Load SampleResources file
        string m = this.GetType().Module.Name;
        m = m.Substring(0, m.Length - 4);
        ResourceManager resourceManager =
            new ResourceManager (m + ".ResourceStrings.SampleResources", 
        int i = (int)e.Value;
        string _SourceName = "";
            case ((int)HE_SourceType.LAN): _SourceName = "LANTask"; break;
            case ((int)HE_SourceType.WebPage): _SourceName = "WebTask"; break;
            case ((int)HE_SourceType.FTP): _SourceName = "FTPTask"; break;
            case ((int)HE_SourceType.eMail): _SourceName = "eMailTask"; break;
            case ((int)HE_SourceType.OCR): _SourceName = "OCRTask"; break;

        //Draw the corresponding image
        Bitmap newImage = (Bitmap)resourceManager.GetObject(_SourceName);
        Rectangle destRect = e.Bounds;
        e.Graphics.DrawImage(newImage, destRect);

public HE_SourceType SourceType
    get{return _SourceType;}
    set{_SourceType = value;}

Drop Down Editor

Visual Studio .NET uses type converters for text-based property editing and code serialization. Some built-in types, such as Color or DockStyle, get a specialized user interface in the property grid as well as text support. If you would like to supply a graphical editing interface for your own property types, you can do so by supplying a UI type editor as a drop-down editor user interface.

First, we create a form to be used as an editor. When initializing the form, we must set its TopLevel property to false. To make it caption-less, we have to set the following properties:

this.MaximizeBox = false;
this.MinimizeBox = false;
this.ControlBox = false;
this.ShowInTaskbar = false;
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

The Contrast property is used in this case.

The following code uses the IServiceProvider passed to EditValue. It asks it for the IWindowsFormsEditorService interface (which is defined in the System.Windows.Forms.Design namespace). This service provides the facility for opening a drop-down editor, we simply call the DropDownControl method on it, and it will open whichever control we pass. It sets the size and location of the control so that it appears directly below the property when the drop-down arrow is clicked.

When we write the UI editor class itself, we have a choice as to the kind of user interface we can supply. We can either open a modal dialog or supply a pop-up user interface that will appear in the property grid itself. We indicate this by overriding the GetEditStyle method. This method returns a value from the UITypeEditorEditStyle enumeration, either Modal or DropDown. For either type of user interface, we must also override the EditValue method, which will be called when the user tries to edit the value. The value returned from EditValue will be written back to the property. It will call EditValue when the arrow button is clicked.

public class ContrastEditor : UITypeEditor
    public override UITypeEditorEditStyle 
           GetEditStyle(ITypeDescriptorContext context)
        return UITypeEditorEditStyle.DropDown;

    public override object EditValue(ITypeDescriptorContext context, 
                            IServiceProvider provider, object value)
        IWindowsFormsEditorService wfes = 
           provider.GetService(typeof(IWindowsFormsEditorService)) as

        if (wfes != null)
            frmContrast _frmContrast = new frmContrast();
            _frmContrast.trackBar1.Value = (int) value;
            _frmContrast.BarValue = _frmContrast.trackBar1.Value;
            _frmContrast._wfes = wfes;

            value = _frmContrast.BarValue;
        return value;


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


About the Author

Ronit H
Israel Israel
No Biography provided

You may also be interested in...


Comments and Discussions

QuestionDynamic Enumeration
George Hendrickson23-May-14 4:20
memberGeorge Hendrickson23-May-14 4:20 
I need to do the dynamic enumeration from data in a database. Is it possible to create a typeconverter for a database driven list that will contain a numeric value and a string(ex: ID and Description)? I can't seem to get that right for some reason.
QuestionHow can i set the value of a combo griditem
M_Mogharrabi1-Oct-13 22:07
memberM_Mogharrabi1-Oct-13 22:07 
I do NOT mean the default value of it! but also i mean the value that was selected in previous time.
QuestionHow is it possible to change size of displaying picture?
kdmitriyval3-Aug-13 1:16
memberkdmitriyval3-Aug-13 1:16 
Thank you for your article about display text & picture in proprtyGrid. But I would like to avoid text and show only image in " like combobox" in grid with width = width of that drop down list. How is it possible to do it? Because I tried to analyse code and I didn't find any points where size is setup. Help me please.
QuestionThank you every much.
yuancx_zjgsu3-Jul-12 13:59
memberyuancx_zjgsu3-Jul-12 13:59 
It is the code I need most. Thank you.
GeneralMy vote of 5
Carl.Hinkle22-Feb-12 12:10
memberCarl.Hinkle22-Feb-12 12:10 
This solved the problem I've been wrestling with all afternoon Smile | :) Thanks!
QuestionAnd how can I make the Contrast value update during sliding?
XtraMarc27-Mar-09 14:01
memberXtraMarc27-Mar-09 14:01 

thanks for the tutorial, it was very helpful to me. I just have the problem, that I'd like to make the int value of Contrast n the Grid Update WHILE I drag the slider. How does that work. The slider doesn't know any more which value he is to update. Could you give me an example?


GeneralJust some other stuff
Huanacaraz8-Apr-08 0:26
memberHuanacaraz8-Apr-08 0:26 
First thanx for this article, it helps me much.
Second - to provide custom UI editor thers no need to design its as Form, but better to use CustomControl, or even any class derived from Control.
(I used ListBox to simulate inline dropdown control to show font list:

static MyObject[] globalarray;
 ListBox Box1;
 IWindowsFormsEditorService wfes;

in constructor:
Box1 = new ListBox();
 Box1.BorderStyle = BorderStyle.None;
 Box1.DrawMode = DrawMode.OwnerDrawFixed;
 Box1.Click += new EventHandler(Box1_Click);
 Box1.DrawItem += new DrawItemEventHandler(Box1_DrawItem);

in EditValue(..)
 wfes = (IWindowsFormsEditorService)...;
 Box1.SelectedItem = value;
 Box1.Height = 150;
 wfes = null;
 if (Box1.SelectedItem != null) return Box1.SelectedItem;

in Box1_Click:

in Box1_DrawItem: (showing font written by self Smile | :)
 MyObject item = (MyObject)Box1.Items[e.Index];
 //provide self font, but take size and format from original...
 using (Font f = item.GetFont(e.Font)) 
   using (Brush b = new SolidBrush(e.ForeColor))
     e.Graphics.DrawString(item.ToString(), f, b, e.Bounds, StringFormat.GenericDefault);

jigs_19711-Apr-08 4:45
memberjigs_19711-Apr-08 4:45 
What a big help, Many thanks.
GeneralCould Be Simpler
sabrown10024-Oct-07 9:38
membersabrown10024-Oct-07 9:38 
It is much easier to perform Dynamic Enumeration than in your sample. Just use an enum as your property type.
GeneralThanks, just saved me hours of work!
Chris Byrne10-Oct-07 3:22
memberChris Byrne10-Oct-07 3:22 
Thanks, just saved me hours of work!Smile | :)
GeneralVB.Net example of dynamic dropdown properties
Tyler W. Cox20-Jul-07 6:35
memberTyler W. Cox20-Jul-07 6:35 
Ronit H was an excellent source for figuring out how to get the property grid to work. If anyone needs a VB.Net example of how to implement dynamic properties I have posted one here:
GeneralNice job
Member #198316831-Jan-07 3:28
memberMember #198316831-Jan-07 3:28 
it is so clear to explain and so goog to be used.

GeneralAvoiding global in dynamic list
cshung17-Jan-07 9:20
membercshung17-Jan-07 9:20 
It is well known that using global is no good, a singleton doesn't make that smell better.
Are there way not to pass the array through global variables.

I attempted, but unfortunately that isn't easy. First, you cannot have non-default constructor for the TypeConverter.
Second, the ITypeDescriptorContext is always null, make it unable to query the Property that it is converting for.

Anyone out there has a good solution for that?
AnswerRe: Avoiding global in dynamic list
zuraw21-Oct-09 3:41
memberzuraw21-Oct-09 3:41 
I agree about globals/singletons, unfortunately most examples on the Web use static objects.
I think best way is to use ITypeDescriptorContext context parameter in EditValue() method to obtain the object that is edited in PropertyGrid (context.Instance).
I don't know why in your case it is null.
In my case the code below works fine:
public override object EditValue( ITypeDescriptorContext context, IServiceProvider provider, object value )
            if( provider != null )
                IWindowsFormsEditorService editorService = provider.GetService( typeof( IWindowsFormsEditorService ) )as IWindowsFormsEditorService;
                if( editorService != null )
                    // context.Instance is the object whose property is being edited 
                    MyClass myObject = (MyClass)context.Instance;
                    // for example, below I use SomeProperty of myObject that is different than property being edited
                    MySelectionControl selectionControl = new MySelectionControl( (int)value, myObject.SomeProperty, editorService );
                    editorService.DropDownControl( selectionControl );
                    value = selectionControl.Value;
            return value;

GeneralVery good work
siroman4-Jan-07 1:15
membersiroman4-Jan-07 1:15 
Useful, clear and direct.
GeneralVery useful (also in combination)
Edddddd21-Nov-06 6:13
memberEdddddd21-Nov-06 6:13 
I would like to mention that I had very good use for this article! It's very clear and I found each of the three parts useful for my project. I combined the Image-ready dropdown field with a custom dropdown window, for some positioning issues in the visual designer I work on.

I hope to find more of these posts come in handy for my job! Excellent!

QuestionLong searched about that... [modified]
tim_mcgwyn22-Aug-06 11:57
membertim_mcgwyn22-Aug-06 11:57 

I'm searched long for a nice demonstration about PropertyGrid - and found now your article Big Grin | :-D Very nice Work -Thanks for that :->

Best Regards

One question: can you tell me please, how I can resized the images (bitmaps) in the _newImage Images (eg. 25, 18)?

-- modified at 4:02 Monday 29th January, 2007

Well nearly 5 months ago and no answer Sigh | :sigh: thats absolutly poor Frown | :(
Your article was very nice but your question-handling aren't


-- modified at 19:30 Saturday 17th February, 2007
nothing to say anymore -> nice article but the handling of the author is really poor

AnswerRe: Long searched about that...
Hypnotron20-Mar-07 10:54
memberHypnotron20-Mar-07 10:54 
Dude, you should be thankful for the free source code. People have lives and you should understand don't exist solely to service your needs.
GeneralRe: Long searched about that...
tim_mcgwyn18-Apr-07 4:19
membertim_mcgwyn18-Apr-07 4:19 
>Dude, you should be thankful for the free source code.
Thanks god for your comment

>People have lives and you should understand don't exist solely to service your needs.

WOW really nice comment (dude). But if someone sets an article in here - I think it will be nice when he (or here she) gives some more information about that stuff!

BTW -> I know that everybody have a live outside !! -> and more I will not say to this note


GeneralRequest for help
tdevip28-Apr-06 1:41
membertdevip28-Apr-06 1:41 
I would like to use a custom-text-box (such as the one that accepts only numeric values) instead of the TextBox provided by the propertyGrid control to edit various properties. How can I achieve this in property gird.

QuestionHow to implement a button (that has 3 dots)?
McMarby18-Apr-06 13:09
memberMcMarby18-Apr-06 13:09 
This is an excellent article.

I have only one question. I have found the way how to display a combox in a propertygrid, but how do I create and show a button that has 3 dots? How do I get the Click-Event of this button?

Thanks a lot.

AnswerRe: How to implement a button (that has 3 dots)? [modified]
adrian7314-Jul-06 23:08
memberadrian7314-Jul-06 23:08 
Change editor type from "DropDown" to "modal", also change the Contrast control to a top level form:
"SampleClasses.cs" of the project:

if (wfes != null)
frmContrast _frmContrast = new frmContrast();

_frmContrast.trackBar1.Value = (int) value;
_frmContrast.BarValue = _frmContrast.trackBar1.Value;
_frmContrast._wfes = wfes;

value = _frmContrast.BarValue;

Form2 _frmContrast = new Form2();

value = _frmContrast.MyValue;

KEYWORDS: PropertyGrid, Modal dialog, 3 dots, Cutom UI Type Editor, DropDown, Modal Dialog Editors derived class -- modified at 4:10 Saturday 15th July, 2006
GeneralEditors Resize Problem
Yaron Sh13-Dec-05 2:42
memberYaron Sh13-Dec-05 2:42 
If the popup form allows resizing (border style is sizable) it can be narrowed but not vice versa.
QuestionHow about inline editing controls
healybd1-Dec-05 11:16
memberhealybd1-Dec-05 11:16 
How would you go about adding inline controls (such as a NumericUpDown) or something else that doesn't really require an entire drop down? I've been beating my head against a wall trying to get this, if you could help me out, I'm sure it would reduce the bruising Wink | ;)
AnswerRe: How about inline editing controls
Yaron Sh13-Dec-05 2:39
memberYaron Sh13-Dec-05 2:39 
I'm not sure I got you correctly but you can design the editor (the form that pops up when the edit button is pressed) using panels etc. as a regular form.
On the form\\editor you can put as much controls as you want with variable size and keep their ratio using their anchors and dock properties.
The type of edit button is returned from the GetEditStyle in the UITypeEditor class.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170215.1 | Last Updated 7 Feb 2005
Article Copyright 2005 by Ronit H
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid