0

How can I databind a GridView to a class like the following?

public class GenericEntity
{
    private readonly Dictionary<string, object> properties = new Dictionary<string, object>();
    public object this[string propertyName]
    {
        get
        {
            if (properties.ContainsKey(propertyName))
                return properties[propertyName];
            else
                return null;
        }
        set
        {
            if (value == null)
                properties.Remove(propertyName);
            else
                properties[propertyName] = value;
        }
    }
}

This class may have any number of properties and there is no way to know any of them on compile time, only on runtime, this is because the properties map directly to columns of a result set from the BD.

How can I databind a list of this GenericEntity class to a GridView? I tried the following but I get the exception of 'class does not contain a property with name...'

var newColumn = new BoundField();
newColumn.HeaderText = resultsetDescription.FieldDisplayName;
newColumn.DataField = resultsetDescription.FieldName;
myGridView.Columns.Add(newColumn);

myGridView.DataSource = GetListOfGenericEntities(args);
myGridView.DataBind();

EDIT:

I have implemented the approach mentioned in this SO answer but it still throws the property exception...

Community
  • 1
  • 1
Andres A.
  • 1,329
  • 2
  • 21
  • 37

1 Answers1

0

If all you need is to bind this generic list to a GridView I would convert this to a DataTable, and then bind the DataTable to the GridView. Have you checked Anonymous Types? You can create a Generic List of Anonymous Types and then bind it to your GridView as well.

Good luck!

Hanlet Escaño
  • 17,114
  • 8
  • 52
  • 75