Question : How can I list all the properties and values of an object in ASP.NET?

Hi Experts

I want to be able to pass any object to a function and have that function loop through its properties and output a list of string values giving each properties name and its value.

How can I achieve this?

Many thanks

Stewart

Answer : How can I list all the properties and values of an object in ASP.NET?

Inorder to read the properties or methods or attributes of an object we should use
using System.Reflection; //Namespace.
Here i'm giving a sample



1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
class testclass
    {
        public string property1
        {
            set;
            get;
        }
        public string property2
        {
            set;
            get;
        }
        public int property3
        {
            set;
            get;
        }
    }

class Program
    {
        static void Main(string[] args)
        {
            //creating object for testclass & setting values to properties
            testclass objtestclass = new testclass();
            objtestclass.property1 = "Value1";
            objtestclass.property2 = "Value2";
            objtestclass.property3 = 120;

            PropertyInfo[] pinfo;            
            pinfo = objtestclass.GetType().GetProperties();
                foreach (PropertyInfo p in pinfo)
                {
                    Console.WriteLine("Property Name: "+p.Name);
                    Console.WriteLine("Property Value: " +p.GetValue(objtestclass, null) + "\n");
                }
                Console.Read();
        }
    }
Random Solutions  
 
programming4us programming4us