views:

410

answers:

1

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?

+1  A: 

Why not use ASP.NET DataBinder that already supports this?

Paul Alexander
I've research many different approaches to using the builtin ASP.NET two-way binding, my approach is very similar to the FormView, but I want the DataSource to be a single item, not an IEnumerable.
bendewey
Sorry...wasn't clear. I was thinking about using the built in DataBinder.Eval method which already supports the sub property naming convention. However to address the IEnumerable issue - you don't have to bind directly to a collection. You can an object directly and then bind to the properties of the object by name.
Paul Alexander