Solved

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

Posted on 2014-12-11
9
167 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
  • 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 29

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
Ransomware-A Revenue Bonanza for Service Providers

Ransomware – malware that gets on your customers’ computers, encrypts their data, and extorts a hefty ransom for the decryption keys – is a surging new threat.  The purpose of this eBook is to educate the reader about ransomware attacks.

 

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 29

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 29

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 29

Expert Comment

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

Featured Post

Migrating Your Company's PCs

To keep pace with competitors, businesses must keep employees productive, and that means providing them with the latest technology. This document provides the tips and tricks you need to help you migrate an outdated PC fleet to new desktops, laptops, and tablets.

Question has a verified solution.

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

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
The article shows the basic steps of integrating an HTML theme template into an ASP.NET MVC project
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

809 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