Search code examples
.netc#-4.0gridviewalignmentdatacolumn

Right Justify a GridView Column Based on column.DataType


I need to right justify all cells in a DataColumn in behind code. I'm generating a large number of tables using a repeater, so I can't hard code the style in to the <td> elements or the css file (to my knowledge).

Ideally I would catch the relevant columns like this;

foreach (DataColumn column in ResultTable.Columns) {

            if (column.DataType == typeof(int))
            {
               //Set the column justification to "right"
            } }

before the repeater is called, but a little googling leaves me with nothing to put in the if statement. I.e. I can't set the style from behind code.

I found a solution to this using javascript for all cells containing an integer number, but as it uses regex to find integers it won't also right justify the column's header. The result of which looks like this for a typical column;

enter image description here

In this case, I need "Count" to be aligned right as well.


Solution

  • I fixed the issue during the Repeater_ItemCreated method. Using a css class to set the alignment.

    var col = new BoundField
    {
     HeaderText = column.ColumnName,
     DataField = column.ColumnName,
    };
    if(column.DataType == typeof(int))
    col.ControlStyle.CssClass = "numericCell";