Tuesday, June 10, 2008

Build SPGridView Columns Dynamically From A View(SPView)

Since the SharePoint 2007 SPGridView controls do not support autogeneration of columns, they typically have to be manually constructed by looping through the datasource and building a column for each field. This is straightforward enough if the datasource is an SPList. For an SPList, you can simple iterate through the Fields collection and add BoundField objects to the grid using the Title and InternalName properties for the HeaderText and DataField respectively.

In the case of an SPView, this is not so straightforward. The challenge is that the view object does not contain the display names of the fields it represents.

So here is how I have worked it out. The SPView object does have a ViewFields property which gives us a collection of the internal names for the fields. So we can use this collection to point to the fields in the parent list to find the other attributes such as the display name (or Title).

private void BuildColumns(SPView myView, SPGridView grid)
{
    SPViewFieldCollection viewFields = myView.ViewFields;
    for (int i = 0; i < viewFields.Count; i++)
    {
        foreach (SPField field in myView.ParentList.Fields)
        {
            if (field.InternalName == viewFields[i])
            {
                if (!field.Hidden)
                {
                    BoundField col = new BoundField();
                    col.HeaderText = field.Title;
                    col.DataField = field.InternalName;
                    grid.Columns.Add(col);
                }
                break;
            }
        }
    }
}

2 comments:

Randy said...

I was looking for the way to find displayname by using SPViewFieldCollection, and your post really helped me alot.
Thank you again.

Ken Duenke said...

Rather than...
"foreach (SPField field in myView.ParentList.Fields)"

You can just...
myView.ParentList.Fields.GetFieldByInternalName(viewFields[i])