AutoFieldGenerators

In 3.5 SP1 we added new properties to GridView and DetailsView which allows the page developer to change the way AutoGenerateColumns creates its columns. This feature is well know in Dynamic Data, but it is not tied to this technology. Dynamic Data takes advantage of this by looking at the meta data that users set on properties to generate columns.

You too can roll your own IAutoFieldGenerator. Lets look at the interface:

public interface IAutoFieldGenerator {

    ICollection GenerateFields(Control control);

}

The interface itself is pretty weird but it gets the job done. GenerateFields takes the control that we're generating the fields for, and expects to get some ICollection of stuff back. If we had the chance to redo this interface we'd probaby rewrite it to be like this:

public interface IAutoFieldGenerator {

    IEnumerable<DataControlField> GenerateFields(Control control);

}

Now it's clear what we expect to get back, but thats besides the point. Lets implement our own.

public class ColumnGenerator : IAutoFieldGenerator {

private IEnumerable<string> _columns;

public ColumnGenerator(IEnumerable<string> columns) {

    _columns = columns ?? Enumerable.Empty<string>();

}

 

public ICollection GenerateFields(Control control) {

    return (from column in _columns

            select new BoundField {

                SortExpression = column,

                HeaderText = column,

                DataField = column

            }).ToArray();

    }

}


We're going to pass a set of column names to our generator that just creates bound fields with the column's name. To make use of our new generator we can just set it like this:

GridView

gridView1.ColumnsGenerator = new ColumnGenerator(Columns);

DetailsView

detailsView1.RowsGenerator = new ColumnGenerator(Columns);

You can do alot of cool things with these generators. Some things I can think of off the top of my head:

  • Hide/Show columns dynamically based on metadata (like what we do with dynamic data)
  • Hide/Show columns based on permissions
  • Create a configurable UI that allows users to hide or show columns based on their preferences.

I've written a sample that allows you to hide or show columns based on a selectable UI. You can download it here:

AutoFieldGenerator.zip

Here is a screen shot of it running.

7 Comments

Comments have been disabled for this content.