Skip to content
Advertisement

How to centrally align the header text of a TemplateField?

I’ve a GridView with TemplateFields.

I have tried HeaderStyle-HorizontalAlign="Center" to align the header text of the TemplateField to center but it’s not working.

<asp:TemplateField HeaderText="Events" HeaderStyle-HorizontalAlign="Center" 
    ItemStyle-HorizontalAlign="Center">
</asp:TemplateField>

How I can align center the header text of a TemplateField?

While ItemStyle-HorizontalAlign="Center" aligning center the items of TemplateField is working correctly.

Any help will be really appreciated!

Advertisement

Answer

The <center> tag is deprecated in HTML 4.01 and not supported in HTML5 – the working code you posted could be “CSS-ified” as follows:

<asp:TemplateField ItemStyle-HorizontalAlign="Center">
    <HeaderTemplate>
        <asp:Panel style="margin-left: auto; margin-right: auto; text-align: center;">
            Events
        <asp:Panel>
    </HeaderTemplate>
<asp:TemplateField>

(Note: Panel is the ASP.Net equivalent of a <div>.)

A slight improvement here is to define a CSS class for the style so it can be reused elsewhere:

.center {
  margin-left: auto;
  margin-right: auto;
  text-align: center;
}

…and reference it from the panel instead of using the inline style:

<asp:Panel CssClass="center">
Advertisement