Click here to Skip to main content
15,879,613 members
Articles / Programming Languages / C#
Article

PropertyGrid and Drop Down properties

Rate me:
Please Sign up or sign in to vote.
4.87/5 (85 votes)
7 Feb 20053 min read 235.1K   6K   150   32
This article discusses three types of drop down properties.

Sample Image - DropDownProperties.jpg

Introduction

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.

C#
internal class HE_GlobalVars
{
    internal static string[] _ListofRules;
}

We also define a type converter as follows:

C#
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:

C#
<Browsable(true)>
[TypeConverter(typeof(RuleConverter))]
public string Rule
{

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

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

C#
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.

C#
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", 
            Assembly.GetExecutingAssembly());
        int i = (int)e.Value;
        string _SourceName = "";
        switch(i)
        {
            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;
        newImage.MakeTransparent();
        e.Graphics.DrawImage(newImage, destRect);
    }
}

[Editor(typeof(SourceTypePropertyGridEditor), 
        typeof(System.Drawing.Design.UITypeEditor))]
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:

C#
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.

C#
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
           IWindowsFormsEditorService;

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

            wfes.DropDownControl(_frmContrast);
            value = _frmContrast.BarValue;
        }
        return value;
    }
}

License

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


Written By
Israel Israel
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionDynamic Enumeration Pin
George Hendrickson23-May-14 3:20
professionalGeorge Hendrickson23-May-14 3:20 
QuestionHow can i set the value of a combo griditem Pin
M_Mogharrabi1-Oct-13 21:07
M_Mogharrabi1-Oct-13 21:07 
QuestionHow is it possible to change size of displaying picture? Pin
kdmitriyval3-Aug-13 0:16
kdmitriyval3-Aug-13 0:16 
QuestionThank you every much. Pin
yuancx_zjgsu3-Jul-12 12:59
yuancx_zjgsu3-Jul-12 12:59 
GeneralMy vote of 5 Pin
Carl.Hinkle22-Feb-12 11:10
Carl.Hinkle22-Feb-12 11:10 
QuestionAnd how can I make the Contrast value update during sliding? Pin
XtraMarc27-Mar-09 13:01
XtraMarc27-Mar-09 13:01 
GeneralJust some other stuff Pin
Huanacaraz7-Apr-08 23:26
Huanacaraz7-Apr-08 23:26 
GeneralWow Pin
Comp@Work1-Apr-08 3:45
Comp@Work1-Apr-08 3:45 
GeneralCould Be Simpler Pin
sabrown10024-Oct-07 8:38
sabrown10024-Oct-07 8:38 
GeneralThanks, just saved me hours of work! Pin
Chris Byrne10-Oct-07 2:22
Chris Byrne10-Oct-07 2:22 
GeneralVB.Net example of dynamic dropdown properties Pin
Tyler W. Cox20-Jul-07 5:35
Tyler W. Cox20-Jul-07 5:35 
GeneralNice job Pin
Member 198316831-Jan-07 2:28
Member 198316831-Jan-07 2:28 
GeneralAvoiding global in dynamic list Pin
cshung17-Jan-07 8:20
cshung17-Jan-07 8:20 
AnswerRe: Avoiding global in dynamic list Pin
zuraw21-Oct-09 2:41
zuraw21-Oct-09 2:41 
GeneralVery good work Pin
siroman4-Jan-07 0:15
siroman4-Jan-07 0:15 
GeneralVery useful (also in combination) Pin
Edddddd21-Nov-06 5:13
Edddddd21-Nov-06 5:13 
QuestionLong searched about that... [modified] Pin
Mc Gwyn22-Aug-06 10:57
Mc Gwyn22-Aug-06 10:57 
AnswerRe: Long searched about that... Pin
Hypnotron20-Mar-07 9:54
Hypnotron20-Mar-07 9:54 
GeneralRe: Long searched about that... Pin
Mc Gwyn18-Apr-07 3:19
Mc Gwyn18-Apr-07 3:19 
GeneralRequest for help Pin
tdevip28-Apr-06 0:41
tdevip28-Apr-06 0: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.

TDP
QuestionHow to implement a button (that has 3 dots)? Pin
McMarby18-Apr-06 12:09
McMarby18-Apr-06 12:09 
AnswerRe: How to implement a button (that has 3 dots)? [modified] Pin
Adrian Pirvu14-Jul-06 22:08
Adrian Pirvu14-Jul-06 22:08 
GeneralEditors Resize Problem Pin
Yaron Sh13-Dec-05 1:42
Yaron Sh13-Dec-05 1:42 
QuestionHow about inline editing controls Pin
healybd1-Dec-05 10:16
healybd1-Dec-05 10:16 
AnswerRe: How about inline editing controls Pin
Yaron Sh13-Dec-05 1:39
Yaron Sh13-Dec-05 1:39 

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

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.