Friday 6 April 2012

Validating Properties In A .Net Propertygrid Control


The easiest way to validate a certain property in a .Net propertygrid control 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));
        }
    }
}

1 comment: