Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
ANTS Performance Profiler 6.0
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Windows Controls » Using Property Grid in C#

Using Property Grid in C#


Property Grid control is one of the control we deal with all the time when writing UI applications. This article and attached source code shows how to use the Property Grid control in your applications.

Author Rank:
Total page views :  207358
Total downloads :  1965
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
PropertyGridExample.zip
 
Become a Sponsor

 

Figure 1 - The property grid in action

Are you familiar with that window in Visual Studio .NET that lets you edit all your forms? You know, the one that you wish you could add to all your programs because it has such a cool interface? You know, the Property Window!  Well guess what? You can add it to your windows form as part of your design and use it to allow users to edit class properties directly because Microsoft has provided it, they just don't display it initially in the toolbox.The control is called the Property Grid and you have full access to it. Simply right click on the toolbox and choose Add/Remove Items... as shown in figure 2 below:

Figure 2 - Adding the Property Grid to the ToolBox

This will bring up the Customize Toolbox dialog which will give you a choice of either .NET Components or COM Components. Scroll down to PropertyGrid, check this item and click OK.Walla! You now have access to a  very powerful editting control in which you can allow users to edit properties in your classes through the slick interface of the property grid.

Figure 3 - Customize ToolBox Dialog for Adding your PropertyGrid Control to the Toolbox

Readying your Class for the Property Grid

The property grid is fairly easy to use.The hard part is making the class that you want to display in the grid "Property Grid Friendly".  The first step is to create public properties for fields you want to expose.  All properties should have get and set methods.(If you don't have a get method, the property won't show up in the PropertyGrid). If you just do the bare minimum of making public properties with get and set methods,  your class instance can be displayed in the property grid.  However, your property grid will be void of descriptions, categories and other niceties that property grids such as Visual Studio.NET contains.  In order to really make your property grid soar, you need to add special attributes to each of your properties.  These attributes are contained in the System.ComponentModel namespace and are shown in the table below:

Attribute Description
CategoryAttribute  This attribute places your property in the appropriate category in a node on the property grid.
DescriptionAttribute This attribute places a description of your property at the bottom of the property grid
BrowsableAttribute This is used to determine whether or not the property is shown or hidden in the property grid
ReadOnlyAttribute Use this attribute to make your property read only inside the property grid

DefaultValueAttribute

Specifies the default value of the property shown in the property grid

DefaultPropertyAttribute

If placed above a property, this property gets the focus when the property grid is first launched. Unlike the other attributes, this attribute goes above the class.

Table 1 - Attributes to ready your class's properties for the property grid

The Customer Class

Now we are ready to create our customer class to make it displayable in the property grid.In order to utilize the property grid attributes in Table 1, we need to import the namespace for these attributes so we add the using clause for the System.ComponentModel:

using System.ComponentModel;

Then we simply create the customer class with private fields and public properties that access these fields. Attributes are placed above the properties to ready each property for the property grid.

Listing 1 - PropertyGrid-Ready Customer Class    

/// <summary>
// Customer class to be displayed in the property grid
/// </summary>
///
[DefaultPropertyAttribute("Name")]
public class Customer
{
private string _name;
private int _age;
private DateTime _dateOfBirth;
private string _SSN;
private string _address;
private string _email;
private bool _frequentBuyer;
// Name property with category attribute and
// description attribute added
[CategoryAttribute("ID Settings"), DescriptionAttribute("Name of the customer")]
public
string Name
{
get
{
return _name;
}
set
{
_name =
value;
}
}
[CategoryAttribute("ID Settings"),
DescriptionAttribute("Social Security Number of the customer")]
public string SSN
{
get
{
return _SSN;
}
set
{
_SSN =
value;
}
}
[CategoryAttribute("ID Settings"),
DescriptionAttribute("Address of the customer")]
public string Address
{
get
{
return _address;
}
set
{
_address =
value;
}
}
[CategoryAttribute("ID Settings"),
DescriptionAttribute("Date of Birth of the Customer (optional)")]
public DateTime DateOfBirth
{
get
{
return _dateOfBirth;
}
set
{
_dateOfBirth =
value;
}
}
[CategoryAttribute("ID Settings"), DescriptionAttribute("Age of the customer")]

public
int Age
{
get
{
return _age;
}
set
{
_age =
value;
}
}
[CategoryAttribute("Marketting Settings"), DescriptionAttribute("If the customer as bought more than 10 times,
this is set to true")]
public bool FrequentBuyer
{
get
{
return _frequentBuyer;
}
set
{
_frequentBuyer =
value;
}
}
[CategoryAttribute("Marketting Settings"), DescriptionAttribute("Most current e-mail of the customer")]
public string Email
{
get
{
return _email;
}
set
{
_email =
value;
}
}
public Customer()
{
}
}

Assigning the PropertyGrid an Object

All that is left to do to get the grid running is assign an instance of our customer class to the property grid.The property grid will automatically figure out all the fields of the customer through reflection and display the property name along with the property value on each line of the grid.  Another nice feature of the property grid is it will create special editing controls on each line that correspond to the value type on that line.For example, a Date of Birth property (of type DateTime) of the customer will allow you to edit the value of the the date with the calendar control.  Booleans can be edited with a combo box showing True or False (saves you from excess typing).

In Listing 2 we created a new customer and populated it with values through its properties.We then use the SelectObject property of the PropertyGrid and assign our customer object to this property.Upon assigning the customer to the grid, the grid will display all of the public properties we defined in our Customer class. 

Listing 2 - Assigning the customer object to the property grid.

private void Form1_Load(object sender, System.EventArgs e)
{
// Create the customer object we want to display
Customer bill = new Customer();
// Assign values to the properties
bill.Age = 50;
bill.Address = " 114 Maple Drive ";
bill.DateOfBirth = Convert.ToDateTime(" 9/14/78");
bill.SSN = "123-345-3566";
bill.Email = bill@aol.com;
bill.Name = "Bill Smith";
// Sets the the grid with the customer instance to be
// browsed
propertyGrid1.SelectedObject = bill;
}

Examining the Results

Figure 1 shows the results of our efforts of creating a property grid in our form.  If we examine figure 1 again we see that the two categories we defined in our CategoryAttribute,ID Settings and Market Settings, are shown as headers in the two tree nodes.The description of the FrequentBuyer is shown at the bottom of the PropertyGrid retrieved from our DescriptionAttribute for the FrequentBuyer property.Upon selecting the boolean FrequentBuyer property value, we get a drop down for the possible boolean values, True or False.

Conclusion

The property grid is a powerful control for allowing users to edit the internals of your published classes.Because of the ability for the property grid to reflect and bind to your class, there is not much work involved in getting the property grid up and working.You can add categories and descriptions to your property grid by using the special grid attributes in the System.Component model.Anyway, here is yet another powerful control available to you and the latest property of your .NET mindshare.


Login to add your contents and source code to this article
 About the author
 
Mike Gold
Michael Gold is President of Microgold Software Inc., makers of the WithClass UML Tool. His company is a Microsoft VBA Partner and Borland Partner. Mike is a Microsoft MVP and founding member of C# Corner. He has a BSEE and MEng EE from Cornell University and has consulted for Chase Manhattan Bank, JP Morgan, Merrill Lynch, and Charles Schwab. Currently he is a senior developer at Finisar Corp. He has been involved in several .NET book projects, and is currently working on a book for using .NET with embedded systems. He can be reached at mike@c-sharpcorner.com
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Become a Sponsor
 Comments
Combo box in a property grid by keerti On February 1, 2007
Hi could you please tel me how we can add a combo box in a property grid??
Reply | Email | Delete | Modify | 
Re: Combo box in a property grid by Jason On March 15, 2007
If you use an enum type then the PropertyGrid creates a combo box.
Reply | Email | Delete | Modify | 
Re: Re: Combo box in a property grid by Andrew On May 4, 2007
Hi! I really need to use ComboBoxed item but I can not use Property of Enum type. (This is because I do not know the entire content of the Combo during the compile time only in a run-time. May be there is possible to create some type inherited from the System.Enum but i do not know exactly how PropertyGrid control will use it and what do I need to overwrite.) Does anybody have any suggestions?
Reply | Email | Delete | Modify | 
Disable the Properties in Property Grid by Swetha On March 30, 2007
how do i Disable a property in a property grid
Reply | Email | Delete | Modify | 
Ty by Mustafa On April 21, 2007
Thank you very much, helped me alot p.s if you could explain how to disable any item we dont want it to be changed, i would be grateful
Reply | Email | Delete | Modify | 
Re: Ty by Tobias On April 24, 2007

Every property wich is read only it self (by having only a get block) is disabled in the grid. If you want to disable a readable property, use the ReadOnlyAttribute.

Reply | Email | Delete | Modify | 
Formatting numbers in the Property Grid by Steffen On June 28, 2007
Hi there. Is it possible to format numbers in the Property Grid i.e. thousands separator and numbers of decimals? Tia Steffen
Reply | Email | Delete | Modify | 
Formatting numbers in the Property Grid by Steffen On June 28, 2007
Hi there. Is it possible to format numbers in the Property Grid i.e. thousands separator and numbers of decimals? Tia Steffen
Reply | Email | Delete | Modify | 
Runtime data in PropertyGrid by padma On July 12, 2007
Hi, I want to populate a propertygrid with data that comes at runtime.By runtime, i mean not only the values, but the filed names also, that is, when the user selects a node from a treeview.
Reply | Email | Delete | Modify | 
how to disable the sort order which is done automatically which setting the object to the selectedobject property.. by sree On August 27, 2007
I want to show the items under the category in my order...like firstname,lastname,dob etc.
Reply | Email | Delete | Modify | 
Re: how to disable the sort order which is done automatically which setting the object to the selectedobject property.. by Varadharajan On September 3, 2007
Is it possible to dynamically add Items (like adding 50 drop down boxes in Property grid) at runtime ? How can I do it ?
Reply | Email | Delete | Modify | 
Property Grid by Varadharajan On September 3, 2007
Is it possible to dynamically add Items (like adding 50 drop down boxes in Property grid) at runtime ? How can I do it ?
Reply | Email | Delete | Modify | 
UiTypeEditor not working with Propertydescriptor by Varadharajan On September 4, 2007
I created Check Boxes in Property Grid using UITypeEditor. I also need to create Property items dynamically , so I used Custom Property creation using PropertyDescriptor class adn created properties using CreateProoperty. The problem is: After using CustomProperty descriptor I am no longer able to see checkboxes or listBoxes created using UIType Editor . Any one have faced this problem before ? How to use UITypeEditor and PropertyDescriptor together in my class and does not lose the UITypeEditor visual (checkboxes, Listboxes) Cheers, Rajan
Reply | Email | Delete | Modify | 
UiTypeEditor not working with Propertydescriptor by Varadharajan On September 4, 2007
I created Check Boxes in Property Grid using UITypeEditor. I also need to create Property items dynamically , so I used Custom Property creation using PropertyDescriptor class adn created properties using CreateProoperty. The problem is: After using CustomProperty descriptor I am no longer able to see checkboxes or listBoxes created using UIType Editor . Any one have faced this problem before ? How to use UITypeEditor and PropertyDescriptor together in my class and does not lose the UITypeEditor visual (checkboxes, Listboxes) Cheers, Rajan
Reply | Email | Delete | Modify | 
hide/disable some properties by Amar On September 4, 2007
How can I hide/disable some elements in property grid for Button or any other control which is a default control
Reply | Email | Delete | Modify | 
check box in property grid by neda On October 30, 2007
hi,could you please tel me hom we canadd a chech box in a propertygrid?
Reply | Email | Delete | Modify | 
Good Article by dattatraya On February 7, 2008
Excellent Article. Keep Posting.
Reply | Email | Delete | Modify | 
HOW TO EDIT APP CONFIG FILE by DEEPTI On February 9, 2008
I M TRYING TO EDIT APP CONFIG FILE AND SAVE THE CHANGES
Reply | Email | Delete | Modify | 
Thank. by howdy_nun On January 28, 2010
thank you verty much. I find this for long time. Thank again.
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.