Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

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

Posted on 2014-12-11
9
Medium Priority
?
187 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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

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

Independent Software Vendors: 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!

Question has a verified solution.

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

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
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…
Have you created a query with information for a calendar? ... and then, abra-cadabra, the calendar is done?! I am going to show you how to make that happen. Visualize your data!  ... really see it To use the code to create a calendar from a q…
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…
Suggested Courses

636 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