Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » Windows Controls C# » 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 :
Page Views : 282119
Downloads : 2920
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
PropertyGridExample.zip
 
 
Team Foundation Server Hosting
Become a Sponsor
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

 

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.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate 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.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
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.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Team Foundation Server Hosting
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 | 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 | 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 | Modify 
Re: Combo box in a property grid by praveen On October 31, 2011
Dear, Please see the article on the below url http://msdn.microsoft.com/en-us/library/aa302326.aspx
Reply | Email | 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 | 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 | 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 | 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 | 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 | 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 | 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 | 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 | 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 | 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 | 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 | 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 | 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 | Modify 
Good Article by dattatraya On February 7, 2008
Excellent Article. Keep Posting.
Reply | Email | 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 | Modify 
Thank. by howdy_nun On January 28, 2010
thank you verty much. I find this for long time. Thank again.
Reply | Email | Modify 
To display a list of strings in the property window of a custom control and to map the selected item of the list in the property window by Tushar On February 12, 2011
I'm creating a custom control in ASP.NET suing C#.NET The control has a property say drives, that shows the list of all drives in the property window. If I select any drive from the "Drive" Property of that control then how can i map the selected Item in the code behind. public List<string> allDrives = new List<string>(); Public List<string> Drive { get { return allDrives; } set { allDrives = value; } } Now, this property of my custom control helps to load the list of drives in the "Drive" property and shows all the list of drives as a collection. If I select any drive then there is another property that loads the list of directories in the another property in that selected drive.
Reply | Email | Modify 
Hiding inherited property by Franz On April 20, 2011
Hi, this tutorial is very easy to understand thanks to you. However, is there a way to hide the inherited property of a user control? I created a user control with a label and a data grid. I just want to display the text property of the label and hide all the other properties within the user control.. I really need your help please.. God Bless
Reply | Email | Modify 
Discover the top 5 tips for understanding .NET Interop
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.