|
|
|
|
|
|
Author Rank:
|
|
Total page views :
207358
|
|
Total downloads :
1965
|
|
|
|
|
Download
Files:
|
|
|
|
|
|
|
|
|
|
|
|
|
Similar ArticlesMost ReadTop RatedLatest
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
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.
|
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.
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|