Solved

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

Posted on 2014-12-11
9
159 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
Comment Utility
BTW the issue is that
var properties = GetProperties(obj);

Open in new window

returns 0 properties.
0
 
LVL 29

Expert Comment

by:anarki_jimbel
Comment Utility
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
Comment Utility
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
 

Author Comment

by:jetbet
Comment Utility
By adding { get; set; } to the declaration of a property I now get the values for that property in the list view.
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 29

Accepted Solution

by:
anarki_jimbel earned 500 total points
Comment Utility
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
Comment Utility
Works perfectly.
Thanks for that.
0
 
LVL 29

Expert Comment

by:anarki_jimbel
Comment Utility
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
Comment Utility
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
Comment Utility
I believe - no.
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

744 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

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now