ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

GetValue

Gets the value of a databinded property-path from an object. The property can have the form "Product.Type.Group".

Source

//method recursively calls nested objects
public static object GetValue(this object o, string path)
{
    var index = path.LastIndexOf('.');

    if (index > 0)
    {
        var propPath = path.Substring(0, index);
        path = path.Substring(index + 1);
        o = GetValue(o, propPath);
    }

    if (o == null)
        return null;

    var property = o.GetType().GetProperty(path);

    var value = property.GetValue(o, null);

    return value;
}

Example

var binding = (column as DataGridBoundColumn).Binding;
var path = binding.Path.Path;
//path is for example "Product.Type.Group";

var currentValue = datarow.GetValue(path);

Author: Chris Meijers

Submitted on: 26 okt. 2010

Language: C#

Type: System.Object

Views: 6294