Jameel Moideen
Jameel Moideen

Reputation: 7931

access dynamic properties of a dynamic class and set value in C#

I am try to create an extension method which accept the parameter as type IEnumerable and try to produce some html string based on number of column and rows count like below

public static  string Grid<T>(IEnumerable<T> collection )
{
    string template = "<div class='loadTemplateContainer' style='display: block;'>"+
                      "<div class='headercontainer'>";
    PropertyInfo[] classProperties = typeof (T).GetProperties();
    foreach (PropertyInfo classProperty in classProperties)
    {
        template = template + "<div class='column style='width: 200px;'>" + 
        classProperty.Name + "</div>";
    }
    template = template + "</div><table class='allTemplateTable'><tbody>";
    string rowTemplate = "";
    foreach (dynamic item in collection)
    {
        rowTemplate = rowTemplate + "<tr>";
        foreach (PropertyInfo classProperty in classProperties)
        {
            var currentProperty = classProperty.Name;      
        }
    }       
}

i want to get value for each property of an item from the collection by property name. how can i achieve it?

Upvotes: 0

Views: 446

Answers (2)

ekostadinov
ekostadinov

Reputation: 6940

Since you are using dynamic and everything is set at run-time - you can consider using reflection. I see you already used PropertyInfo so maybe you can extend it like this:

public static object GetPropValue(object src, string propName)
{
    return src.GetType().GetProperty(propName).GetValue(src, null);
}

and use in the Iterator to get the value you need.

Upvotes: 2

L.B
L.B

Reputation: 116098

It can be done by something like:

public static string Grid<T>(IEnumerable<T> collection)
{
    ...........
    ...........

    foreach (T item in collection)
    {
        foreach (var p in classProperties )
        {
            string s = p.Name + ": " + p.GetValue(item, null);
        }
    }
}

Upvotes: 3

Related Questions