Chris Moutray Chris Moutray - 1 year ago 67
C# Question

Data binding dynamic data

I have a set of 'dynamic data' that I need to bind to the GridControl. Up until now, I have been using the standard DataTable class that's part of the System.Data namespace. This has worked fine, but I've been told I cannot use this as it's too heavy for serialization across the network between client & server.

So I thought I could easy replicate a 'cut-down' version of the DataTable class by simply having a type of

List<Dictionary<string, object>>
whereby the List represents the collection of rows, and each Dictionary represents one row with the column names and values as a KeyValuePair type. I could set up the Grid to have the column DataField properties to match those of the keys in the Dictionary (just like I was doing for the DataTable's column names.

However after doing

gridControl.DataSource = table;
gridControl.RefreshDataSource();


The grid has no data...

I think I need to implement
IEnumerator
- any help on this would be much appreciated!

Example calling code looks like this:

var table = new List<Dictionary<string,object>>();

var row = new Dictionary<string, object>
{
{"Field1", "Data1"},
{"Field2", "Data2"},
{"Field3", "Data3"}
};

table.Add(row);

gridControl1.DataSource = table;
gridControl1.RefreshDataSource();

Answer Source

Welcome to the wonderful world of System.ComponentModel. This dark corner of .NET is very powerful, but very complex.

A word of caution; unless you have a lot of time for this - you may do well to simply serialize it in whatever mechanism you are happy with, but rehydrate it back into a DataTable at each end... what follows is not for the faint-hearted ;-p

Firstly - data binding (for tables) works against lists (IList/IListSource) - so List<T> should be fine (edited: I misread something). But it isn't going to understand that your dictionary is actually columns...

To get a type to pretend to have columns you need to use custom PropertyDescriptor implementations. There are several ways to do this, depending on whether the column definitions are always the same (but determined at runtime, i.e. perhaps from config), or whether it changes per usage (like how each DataTable instance can have different columns).

For "per instance" customisation, you need to look at ITypedList - this beast (implemented in addition to IList) has the fun task of presenting properties for tabular data... but it isn't alone:

For "per type" customisation, you can look at TypeDescriptionProvider - this can suggest dynamic properties for a class...

...or you can implement ICustomTypeDescriptor - but this is only used (for lists) in very occasional circumstances (an object indexer (public object this[int index] {get;}") and at least one row in the list at the point of binding). (this interface is much more useful when binding discrete objects - i.e. not lists).

Implementing ITypedList, and providing a PropertyDescriptor model is hard work... hence it is only done very occasionally. I'm fairly familiar with it, but I wouldn't do it just for laughs...


Here's a very, very simplified implementation (all columns are strings; no notifications (via descriptor), no validation (IDataErrorInfo), no conversions (TypeConverter), no additional list support (IBindingList/IBindingListView), no abstraction (IListSource), no other other metadata/attributes, etc):

using System.ComponentModel;
using System.Collections.Generic;
using System;
using System.Windows.Forms;

static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        PropertyBagList list = new PropertyBagList();
        list.Columns.Add("Foo");
        list.Columns.Add("Bar");
        list.Add("abc", "def");
        list.Add("ghi", "jkl");
        list.Add("mno", "pqr");

        Application.Run(new Form {
            Controls = {
                new DataGridView {
                    Dock = DockStyle.Fill,
                    DataSource = list
                }
            }
        });
    }
}
class PropertyBagList : List<PropertyBag>, ITypedList
{
    public PropertyBag Add(params string[] args)
    {
        if (args == null) throw new ArgumentNullException("args");
        if (args.Length != Columns.Count) throw new ArgumentException("args");
        PropertyBag bag = new PropertyBag();
        for (int i = 0; i < args.Length; i++)
        {
            bag[Columns[i]] = args[i];
        }
        Add(bag);
        return bag;
    }
    public PropertyBagList() { Columns = new List<string>(); }
    public List<string> Columns { get; private set; }

    PropertyDescriptorCollection ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors)
    {
        if(listAccessors == null || listAccessors.Length == 0)
        {
            PropertyDescriptor[] props = new PropertyDescriptor[Columns.Count];
            for(int i = 0 ; i < props.Length ; i++)
            {
                props[i] = new PropertyBagPropertyDescriptor(Columns[i]);
            }
            return new PropertyDescriptorCollection(props, true);            
        }
        throw new NotImplementedException("Relations not implemented");
    }

    string ITypedList.GetListName(PropertyDescriptor[] listAccessors)
    {
        return "Foo";
    }
}
class PropertyBagPropertyDescriptor : PropertyDescriptor
{
    public PropertyBagPropertyDescriptor(string name) : base(name, null) { }
    public override object GetValue(object component)
    {
        return ((PropertyBag)component)[Name];
    }
    public override void SetValue(object component, object value)
    {
        ((PropertyBag)component)[Name] = (string)value;
    }
    public override void ResetValue(object component)
    {
        ((PropertyBag)component)[Name] = null;
    }
    public override bool CanResetValue(object component)
    {
        return true;
    }
    public override bool ShouldSerializeValue(object component)
    {
        return ((PropertyBag)component)[Name] != null;
    }
    public override Type PropertyType
    {
        get { return typeof(string); }
    }
    public override bool IsReadOnly
    {
        get { return false; }
    }
    public override Type ComponentType
    {
        get { return typeof(PropertyBag); }
    }
}
class PropertyBag
{
    private readonly Dictionary<string, string> values
        = new Dictionary<string, string>();
    public string this[string key]
    {
        get
        {
            string value;
            values.TryGetValue(key, out value);
            return value;
        }
        set
        {
            if (value == null) values.Remove(key);
            else values[key] = value;
        }
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download