I have been working on a project recently that require the use of the SPGridView web control and realise that it doesn’t auto generate columns for you, even if you set the property to true it will complain. So to overcome this issue I had to write a some code to achieve what I want it to do.

First I need to use the BoundField for setting up the column and binding to a SharePoint List and there is two properties that I need to set, which is the HeaderText for the column display text and DataField for binding to the list’s field.

To set these two properties I need to instantiate a SPList and get the list’s SPView object that I need, when I have the SPView object I can iterate through the ViewFields collection to get each of the field internal names for setting the DataField property and to get the display name I had to take the current list’s SPField collection and use a method called GetFieldByInternalName to return a SPField. Then I use the SPField Title property to set the HeaderText property.

private void GenerateColumns(SPGridView spGridView, string listName, string viewName)
    var spWeb = SPContext.Current.Web;
    var spList = spWeb.Lists[listName];
    var spView = spList.Views[viewName];
    var spFields = spList.Fields;

    foreach (string intNameField in spView.ViewFields)
        var spField = spFields.GetFieldByInternalName(intNameField);
        if (spField != null)
            var boundField = new BoundField
                    HeaderText = spField.Title,
                    DataField = intNameField

Now I have the created method to auto generate the columns I need to make sure the datasource I am binding to the SPGridView control contains the same internal field name of the list or else the code above won’t work.