Solved

c# VS2013 Getting all properties names and values from a class.

Posted on 2014-12-11
9
174 Views
Last Modified: 2014-12-12
I have created a series of objects to store current information and want a way to see the names and values of the properties at various levels.
I am using a TreeView to be able to drill down into the structure. Each node contains the underlying object in it's TAG property.
What I want to do is click on the node and then this will access the properties and print them out to a list view.
The code I am using is
private void TV_Main_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode selected = TV_Main.SelectedNode;
            if (selected != null)
            {
                LV_MainProperties.Items.Clear();
                if (selected.Tag != null)
                {
                    Object obj = selected.Tag;
                    var properties = GetProperties(obj);

                    foreach (var p in properties)
                    {
                        try
                        {
                            string name = p.Name;
                            var value = p.GetValue(obj, null);
                            AddDataItem(LV_MainProperties, new List<String> { name, value.ToString() });
                        }
                        catch
                        {

                        }
                    }
                }
            }  

        }

private static PropertyInfo[] GetProperties(object obj)
        {
            return obj.GetType().GetProperties();
        }

       

        private void AddDataItem(ListView listView, List<String> data)
        {
            if (data.Count > 0)
            {
                ListViewItem temp = new ListViewItem(data[0]);
                for (int i = 1; i < data.Count; i++)
                {
                    temp.SubItems.Add(data[i]);
                }
                listView.Items.Add(temp);
            }
        }

Open in new window


This works for a couple of classes only. Does anyone know why this code is not robust enough to work in all circumstances?
0
Comment
Question by:jetbet
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
9 Comments
 

Author Comment

by:jetbet
ID: 40494747
BTW the issue is that
var properties = GetProperties(obj);

Open in new window

returns 0 properties.
0
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 40494771
The method returns an empty array of type PropertyInfo, if the current Type does not have public properties.

So may be it worth to check class declarations?

Just in case, you may need to consider the overloaded method:

http://msdn.microsoft.com/en-us/library/kyaxdd3x(v=vs.110).aspx
0
 

Author Comment

by:jetbet
ID: 40494791
There are definitely public properties on these classes.
Start of a class declaration that returns an empty array.
 [Serializable]
    public class EventDetails
    {
        static readonly object _locker = new object();

        public RequestStream requestStream;
        public String meeting;
        public String meetingName;
        public String meetingCountry;
        public String number;
        public String name;
        public DateTime dateTime;
        public DateTime meetingDateTime;
....

Open in new window



Start of a class declaration that does not return an empty array.
[Serializable]
    public class RunnerDetail
    {
        static readonly object _locker = new object();

        RequestStream requestStream;
        String system;
        String systemId;
        String meeting;
        String race;

        RunnerProfile profile;

        public int number { get; set; }

        public String name { get; set; }
        public String meetingCountry { get; set; }
        public WinMovers winMovers { get; set; }
        public QLADetails qlaOdds { get; set; }
        public String form { get; set; }
        public String barrier { get; set; }
        public String handicap { get; set; }
        public String formattedBarrier { get; set; }
        public String person { get; set; }
        public String personShort { get; set; }

Open in new window

0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:jetbet
ID: 40494798
By adding { get; set; } to the declaration of a property I now get the values for that property in the list view.
0
 
LVL 30

Accepted Solution

by:
anarki_jimbel earned 500 total points
ID: 40494813
You may try to use GetFields() method to retrieve field values for:

        public RequestStream requestStream;
        public String meeting;
        public String meetingName;
                  etc.

Open in new window



See http://msdn.microsoft.com/en-us/library/system.type.getfields(v=vs.110).aspx
0
 

Author Closing Comment

by:jetbet
ID: 40494863
Works perfectly.
Thanks for that.
0
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 40494864
BTW, you need to distinguish between fields and properties.

Properties expose fields. Fields preferably should be kept private to a class and accessed via properties. Properties provide a level of abstraction allowing you to change the fields while not affecting the external way they are accessed by the things that use your class.

public class MyClass
{
    // this is a field that stores the actual data.
    private string _myField;

    // this is a property
    public string MyField
    {
        get
        {
            return _myField;
        }
        set
        {
            _myField = value;
        }
    }
}

Open in new window

0
 

Author Comment

by:jetbet
ID: 40495305
Thanks for that.

Are there any differences in declaring the fields
int _number = 0;
        public int number
        {
            get { return _number;}
            set { _number = value; }
        }
over
        public String number { get; set; }

if I am not doing validation at this stage.
0
 
LVL 30

Expert Comment

by:anarki_jimbel
ID: 40495809
I believe - no.
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Where is this file? 3 33
Unlocking a column in excel using C# 17 28
c# DateTime Format validation 4 69
C# LINQ 5 27
Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
Summary: Persistence is the capability of an application to store the state of objects and recover it when necessary. This article compares the two common types of serialization in aspects of data access, readability, and runtime cost. A ready-to…
Attackers love to prey on accounts that have privileges. Reducing privileged accounts and protecting privileged accounts therefore is paramount. Users, groups, and service accounts need to be protected to help protect the entire Active Directory …

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question