SPGridView: How to Auto Generate Columns

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.

Sorting GridView using IComparer and Reflection

Recently I just did a small job for a client online using IComparer interface to perform sorting on a GridView control.

First I need to create class called Person. This class is going to contain the following properties: FirstName, LastName, Age.

public class Person
    private string _firstName;
    private string _lastName;
    private int _age;

    public string FirstName
        get { return _firstName; }
        set { _firstName = value; }

    public string LastName
       get { return _lastName; }
       set { _lastName = value; }

    public int Age
       get { return _age; }
       set { _age = value; }

Now I need to create a class called PersonComparer that will inherit from the IComparer interface. This comparer class will be use with the Sort() method from a List collection.

 using System.Collections;
 using System.Collections.Generic;
 using System.Reflection;
 using System;

 public class PersonComparer:IComparer
     private string _sortBy;

     public string SortBy
         get { return _sortBy; }
         set { _sortBy = value; }

     public int Compare(Person x, Person y)
         int result = 0;
         string propName = string.Empty;
         string sortDirection = "ASC";

         if (_sortBy.Contains(" DESC"))
             propName = _sortBy.Replace(" DESC", string.Empty).Trim();
             sortDirection = "DESC";

         if (_sortBy.Contains(" ASC"))
             propName = _sortBy.Replace(" ASC", string.Empty).Trim();
             sortDirection = "ASC";

         // Get type of Person Object
         Type t = typeof(Person);

         // Find the property name from the sortExpress passed in SortBy property.
         PropertyInfo propInfo = t.GetProperty(propName);

         if (propInfo != null)
             // Perform comparison on property value.
             result = Comparer.DefaultInvariant.Compare(propInfo.GetValue(x, null), propInfo.GetValue(y, null));

             if (sortDirection.Equals("DESC"))
                 result = -result;
         return result;


ASP.NET: Cache or Session

What the difference between Cache and Session variables. Cache variables are available at the application level which means that another web user can access the same cache. Session variables are available at the client level which only the client can read or write to the Session variable.

When developing a web application in ASP.NET it’s good practice to use Cache to store data that will be shared across the application. For example if you need to read from cache a list of colour names from a table from a database, you can reuse this cache when ever your page loads. This way it prevents repetitive reads from the table which can reduce web application performance.

List<string> colourList = new List<string>();

Cache["ColourList"] = colourList;

colourList = Cache["ColourList"] as List<string>;

Session variables are used for storing user specific data such as user’s details, below is an example of how it’s used.

Session["Username"] = "joe.bloggs";

string username = Session["Username"].ToString();

Make sure you understand the difference between them two and which one to use for your purpose, never store user’s details in a Cache variable because another web user can access them but then this means that the web was poorly designed.

For further reading on Cache and Session variables I came across some web sites that may be resourceful:

ASP.NET Session State Overview

ASP.NET Caching