Welcome to Devintelligence.com Sign in | Join | Help

.Net Adventures

In .Net we trust
Your Cheap Web Hosting Solution


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: , ,
Posted: Saturday, January 27, 2007 5:01 PM by adventurer

Comments

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# March 24, 2007 7:29 AM
New Comments to this post are disabled