?
Solved

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

Posted on 2014-12-11
9
Medium Priority
?
181 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
Industry Leaders: 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 2000 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

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

Article by: Najam
Having new technologies does not mean they will completely replace old components.  Recently I had to create WCF that will be called by VB6 component.  Here I will describe what steps one should follow while doing so, please feel free to post any qu…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…

777 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