Validating properties in a PropertyGrid control

The easiest way to validate a certain property is using the PropertyValueChanged event.The code bellow shows how to limit the valid range of Age property to be 1-150

using System.Windows.Forms; 
namespace WindowsApplication1 
{ 
    public partial class Form1 : Form 
    { 
        public Form1() 
        { 
            InitializeComponent(); 
            //init person object  
            Person person = new Person(); 
            person.FirstName = "George"; 
            person.Age = 33; 
            propertyGrid.SelectedObject = person; 
            propertyGrid.PropertyValueChanged+=  new PropertyValueChangedEventHandler( propertyGrid_PropertyValueChanged ); 
        } 
 
        private void propertyGrid_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) 
        { 
            if (e.ChangedItem.Label == "Age" && !IsAgeValid((int)e.ChangedItem.Value) ) 
            { 
                // the entered age value is wrong - show error message 
                e.ChangedItem.PropertyDescriptor.SetValue( propertyGrid.SelectedObject, e.OldValue); 
                MessageBox.Show("Wrong age", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); 
            } 
        } 
 
        ///<summary>
        /// Determines whether age is valid 
        /// </summary>  
        /// <param name="age">The age.</param>  
        /// <returns>  
        /// <c>true</c> if is age valid ; otherwise, <c>false</c>. 
        /// </returns>  
        private static bool IsAgeValid( int age ) 
        { 
            return ((age > 0) && (age < 150)); 
        } 
    } 
}

 

Technorati tags: propertygrid, dotnet, programming


 
 
 

2 Responses to “Validating properties in a PropertyGrid control”

  1. Andrea Ferroni
    23. February 2010 at 16:12

    …ok, but if I insert the letters in the numeric field, I get a type mismatch error.
    That check happens before the PropertyValueChanged event.
    How to intercept that check ?

  2. Don Jose
    15. December 2011 at 22:29

    You will need to implement a TypeConverter and add it as an attribute to the class property of your object that is assigned to the PropertyGrid.

    This link shows you how:
    http://social.msdn.microsoft.com/forums/en-US/winforms/thread/afcd4dd5-5538-433b-8cac-78c081ee16b6/

Leave a Reply