On Thu, 22 May 2008 06:05:00 -0700, WebBuilder451
<We***********@discussions.microsoft.comwrote:
>I have a custom business object of type Person.
i created a page with check boxes that will post to a second page that is
strongly typed with the first page and i have a function that retreives all
the checked boxes from the first page. The ID value of each checkbox is the
name of a property in the business object (Name, Address, Phone, ...). I can
get all the ids no problem here.
Question is there a way to convert or evaluate a string value to get an the
object property? ... So that:
Person PER = new Person(); // use default consrtructor here
string str = PER + ".Name"; will give me PER.Name?
This is called reflection. First, you will need to get an object of
type "Type" that describes the class Person - this is done using
typeof(Person).
Then, use the GetProperty(string propertyName) method of the type
object to retrieve a PropertyInfo class by name.
Finally, use the GetValue method of the PropertyInfo class to get the
value for a given instance of "Person".
Since this is rather abstract, here is a concrete example that will
(hopefully) make things clearer:
using System;
using System.Reflection;
namespace ConsoleApplication1
{
class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
class Program
{
static void Main(string[] args)
{
Person p = new Person();
p.FirstName = "Anders";
p.LastName = "Hjelsberg";
Type personType = typeof(Person);
string propertyToRetrieve = "FirstName";
PropertyInfo propertyInfo =
personType.GetProperty(propertyToRetrieve);
object retrievedValue = propertyInfo.GetValue(p, null);
Console.WriteLine("{0} = {1}", propertyToRetrieve,
retrievedValue);
Console.ReadKey();
}
}
}
Regards,
Gilles.