简体   繁体   中英

How do I use reflection to get the nested property

I am writing a TwoWay Binding control for ASP.NET. I finally got things working. I'm rebinding using the following code:

private void RebindData()
{
    // return if the DataValue wasn't loaded from ViewState
    if (DataValue == null)
        return;
    // extract the values from the two-way binding template
    IOrderedDictionary values = new OrderedDictionary();
    IBindableTemplate itemTemplate = DataTemplate as IBindableTemplate;
    if (itemTemplate != null)
    {
        foreach (DictionaryEntry entry in itemTemplate.ExtractValues(this))
        {
            values[entry.Key] = entry.Value;
        }
    }

    // use reflection to push the bound fields back to the datavalue
    foreach(var key in values.Keys)
    {
        var type = typeof(T);
        var pi = type.GetProperty(key.ToString());
        if (pi != null)
        {
            pi.SetValue(DataValue, values[key], null);
        }
    }
}

This works for the simple cases like this:

<%# Bind("Name") %>

The reflection technique I'm using isn't working when I have a nested binding statement like this:

<%# Bind("Customer.Name") %>

Is there an easy way to use reflection for nested properties like this? Should I use a recursive function for this, or just a loop?

为什么不使用已经支持此功能的ASP.NET DataBinder?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM