Monday, July 14, 2008

Format GridView column header text automatically

Here is a snippet of code that I use for with GridViews to convert Database column names to User friendly text. This comes in handy when I am too lazy or not enough time to go through and change the names of the automatically generated column names that are shown as the column headers in a GridView. This also makes it easy to keep the text looking nice even when the columns change and the columns get regenerated. I realize there are some downsides, like slight performance hit, etc, but for departmental solutions were development time is the most precious thing I have, this is a time saver.

This method assumes that your column names are in Pascal Case. This means that all columns start with a capital letter, and that each word in the column name starts with a capital as well. Everything else in between should be lowercase. An example of this is FirstName or LastName or or ZipCode or DisplayName.

// assumes that source text is in PascalCase and that it
// should be changed to more human readable capitalization.
// i.e. BrentVermilion is in pascal case and a more human
// readable form is Brent Vermilion
public static string MakeUserFriendly(string text)
 StringBuilder sb = new StringBuilder(text);
 int insertAdjustment=0;
 char ch;
 for (int i = 0; i < text.Length; i++ )
  // AND the previous letter wasn't an Uppercase letter
  if (!char.IsUpper(text[i - 1]))
   // insert a space before the uppercase letter
   sb.Insert(i + insertAdjustment, ' ');
   // we need to keep track of how many space we have added
   // so we know what the adjusted index to insert at will be
 return sb.ToString();

One place you can call this method is in the PageLoad event.

protected void Page_Load(object sender, EventArgs e)
 if (!Page.IsPostBack)
  // convert cryptic Pascal Case header column text
  // (what the user sees) to User friendly readable text
  for (int i = 0; i < myGridView.Columns.Count; i++)
   myGridView.Columns[i].HeaderText =


C.L. Moffatt said...

A much simpler way would be to just do this in the .aspx file:

<asp:BoundField DataField="AvgPrice" SortExpression="AvgPrice" DataFormatString="{0:c2}"
HeaderText="Price (Average)">

Where the DataField is the name of the column in the database and HeaderText is what you actually want to appear in the table header.

Brent V said...

Hi c.l. moffatt,

Thank you for your response. I think we are talking about different scenarios. You make a good point though. However, since these are auto-generated columns that I am talking about by the GridView, I don't have them in the .aspx file.

Consider the case where you don't actually know what columns you will be displaying because they are based on the query and you pass different queries.

This is not perfect code and you are right it certainly doesn't apply if you have the boundfield tags in you .aspx file (like in the case when the columns are not auto-generated).