GridView - Set column properties at run-time

An interesting issue came up today that, although it now looks simple, did not have an immediately obvious solution. Specifically, what if you want to set properties of individual columns of a GridView at run-time (via C# code) rather than at design time in the aspx code.

For example, let's say you want to set the DataFormatString property of a BoundField column. In short, it is a 2-part solution. First, you must positionally extract your column out of the GridView's Columns property while casting it to your desired type (in this case a BoundField). Second, after you have set the properties, do the databind. So if you have column that you want to format as currency, the code might look like this:

BoundField priceField = grid.Columns[0] as BoundField;  
priceField.DataFormatString = "{0:c}";  
priceField.HtmlEncode = false;  
grid.DataSource = list;  

Note that since you're manually doing the data binding this will preclude you from using the ObjectDataSource in this case (since that happens before your user code in the Page_Load event).

Taking this one step further, you could even add columns dynamically at run-time doing this:

BoundField someField = new BoundField();  
someField.DataField = "Price";  
someField.DataFormatString = "{0:c}";  
someField.HtmlEncode = false;  

Note: One reason this might throw you off at first is that in the C# intellisense, BoundColumn comes up first and if you're not watching carefully you might try to use that instead of BoundField which will prevent you from compiling!

Tweet Post Share Update Email RSS