access to member of a class by name;

D

danmath06

If I have an Object and a string wich is the name of a member of the
object, how can I access the member. I'm trying to do something
similar to the DisplayMember property the ListBox has. I'm adding some
functionality to the ListView control, and I would like it to have a
method that takes a collection of objects and an array of member names
to know which members to display.
 
D

danmath06

Changed my mind:
I want to add 2 methods
1- addcolumn (column_name, width, display member)
2- additems (collection)
 
D

danmath06

You'll need reflection for that. You can call GetType() on the object,
then call Type.GetMember() on that Type instance to retrieve information
about the actual member, from which you can then do whatever you need to
get a value for your purposes.

You might want to consider limiting the feature to properties. That would
simplify the code doing the reflection, as well as encourage clients of
your class to encapsulate things better. :) In that case, you can just
call Type.GetProperty() instead.

Pete

thanks pete.

I tried this as a test and it worked:

private void getmember (object o, string member){

Type type = o.GetType();

System.Reflection.PropertyInfo info =
type.GetProperty("Nombre");


MessageBox.Show(info.GetValue(o,null).ToString());

}
 
D

danmath06

thanks pete.

I tried this as a test and it worked:

private void getmember (object o, string member){

Type type = o.GetType();

System.Reflection.PropertyInfo info =
type.GetProperty("Nombre");

MessageBox.Show(info.GetValue(o,null).ToString());

}

I meant 'member' not 'nombre':

private void getmember (object o, string member){

Type type = o.GetType();

System.Reflection.PropertyInfo info =
type.GetProperty(member);


MessageBox.Show(info.GetValue(o,null).ToString());

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top