c ා display the properties of the class on PropertyGrid

When we use the PropertyGrid control, we usually use common types such as: int, string, bool to display the properties of this class in the PropertyGrid through the following code

   public partial class Form1 : Form
    	{
    		public Form1()
    		{
    			InitializeComponent();
    			Student stu = new Student();
    			proGrid.SelectedObject = stu;
    		}
    	}
    
    	public class Student
    	{
    		private string name = "Tom";
    		public string Name
    		{
    			get
    			{
    				return name;
    			}
    			set
    			{
    				name = value;
    			}
    		}
    
    		private int stuID = 05;
    		public int StuID
    		{
    			get
    			{
    				return stuID;
    			}
    			set
    			{
    				stuID = value;
    			}
    		}
    		private bool isBoy = true;
    		public bool IsBoy
    		{
    			get
    			{
    				return isBoy;
    			}
    			set
    			{
    				isBoy = value;
    			}
    		}
    	}

The effect is as follows

Here's the question: what if we define a class type property in the Student class?

Solution: add [TypeConverter(typeof(ExpandableObjectConverter)) above the properties of our class type]
Create a Lily class first

public class Lily
	{
		private int stuID = 04;
		public int StuID
		{
			get
			{
				return stuID;
			}
			set
			{
				stuID = value;
			}
		}
		private string name = "Lily";
		public string Name
		{
			get
			{
				return name;
			}
			set
			{
				name = value;
			}
		}
		public override string ToString()
		{
			return "...";
		}
	}

Next is the code for the class type“

public class Student
	{
	    //Name
		private string name = "Tom";
		public string Name
		{
			get
			{
				return name;
			}
			set
			{
				name = value;
			}
		}
       //ID
		private int stuID = 05;
		public int StuID
		{
			get
			{
				return stuID;
			}
			set
			{
				stuID = value;
			}
		}
		//Is it a boy
		private bool isBoy = true;
		public bool IsBoy
		{
			get
			{
				return isBoy;
			}
			set
			{
				isBoy = value;
			}
		}
		//Lily type
		Lily myLily = new Lily();
		[TypeConverter(typeof(ExpandableObjectConverter))] 
		[EditorBrowsable(EditorBrowsableState.Always)]
		public Lily MyLily
		{
			get
			{
				return myLily;
			}
			set
			{
				myLily = value;
			}
		}
	}

The renderings are as follows:

This article references from https://www.codeproject.com/Articles/271589/Show-Properties-of-a-Class-on-a-PropertyGrid

Posted by Shane10101 on Sat, 28 Dec 2019 06:30:33 -0800