Results 1 to 3 of 3

Thread: [RESOLVED] Looping through an Object

  1. #1

    Thread Starter
    Member
    Join Date
    Mar 2006
    Posts
    58

    Resolved [RESOLVED] Looping through an Object

    I have created a Consumer Object and I would like to loop through and display each property. So in my sample code I would like to have 2 message boxes displayed one with "ekim" another with "12987". But my object array, attributes, is always null. Is there a correct way to loop through an object?

    public void Testing()
    {
    CConsumer Consumer = new CConsumer();
    Consumer.FirstName = "ekim";
    Consumer.LastName = "12987";

    System.Reflection.MemberInfo inf = typeof(CConsumer);
    object[] attributes;
    attributes = inf.GetCustomAttributes(typeof(CConsumer), false);

    foreach (Object attribute in attributes)
    {
    MessageBox.Show(attribute.ToString());
    }
    }

    Thanks

  2. #2
    I'm about to be a PowerPoster! mendhak's Avatar
    Join Date
    Feb 2002
    Location
    Ulaan Baator GooGoo: Frog
    Posts
    38,170

    Re: Looping through an Object

    You would use PropertyInfo.

    Code:
    Type objType = Consumer.GetType();
    PropertyInfo[] pi = objType.GetProperties();
    foreach(PropertyInfo p in pi)
    {
    //Now, use p.
    }

  3. #3

    Thread Starter
    Member
    Join Date
    Mar 2006
    Posts
    58

    Re: Looping through an Object

    Thanks for the response. To display the value just use GetValue


    foreach (PropertyInfo p in pi)
    {
    MessageBox.Show(p.GetValue(Consumer, null).ToString());

    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width