Align Header Text Center asp:GridView

12,669

Solution 1

Can you try this code to the template fields in aspx?

ItemStyle-HorizontalAlign="Center"

Solution 2

Sometimes accepted answer will not do the job (css is forced by style sheet and/or skin file). In this case you can set custom css class (if you want to align specific column):

.alignRight {
    text-align: right !important;
}

Next you need to attach to your GridView RowDataBound Event and set css on specific Column:

    protected void SumGridView_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            string forcedCss = "alignRight";

            //TODO: change your col index:
            e.Row.Cells[2].CssClass = forcedCss;
        }
    }
Share:
12,669
Alina Anjum
Author by

Alina Anjum

Experienced in dot NET Technology with more than 5 years of Experience in IT Industry. I have the Experience of developing Desktop & Web Based Applications using: ASP.NET C#, SQL SERVER, SharePoint on-Premise 2013 and 2016, Custom Web Part Development in Microsoft SharePoint. I am Masters in Software Engineering Fiverr Profile: https://www.fiverr.com/alinaanjum

Updated on June 28, 2022

Comments

  • Alina Anjum
    Alina Anjum almost 2 years

    I am displaying some content in gridview , everything is working fine except the alignment of the grid.

    I am trying to center-align the text of Header but nothing is working fine.

    I tried this :

     <asp:GridView ID="Gv_Edu" runat="server" BackColor="White" AutoGenerateColumns="false"
       BorderColor="#000000" BorderStyle="Solid" BorderWidth="1px" CellPadding="4"
      ForeColor="Black" OnRowDataBound="Gv_Edu_RowDataBound">
      <Columns>
    <asp:TemplateField HeaderText="Sr.No">
    <HeaderStyle HorizontalAlign="Center" />
    <ItemTemplate>
       <asp:Label runat="server" ID="srlbl" Text='<%#Container.DataItemIndex+1 %>'></asp:Label>
    <ItemTemplate>
      <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="10%" />
      </asp:TemplateField>
        <asp:BoundField HeaderText="Degree / Certificate" DataField="deg">
       <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="30%" />
      </asp:BoundField>
        <asp:BoundField HeaderText="Institute" DataField="inst">
        <HeaderStyle HorizontalAlign="Center" />
         <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="20%" />
        </asp:BoundField>
        <asp:BoundField HeaderText="Program Duration" DataField="term">
          <HeaderStyle HorizontalAlign="Center" />
          <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="10%" />
           </asp:BoundField>
          </Columns>
     <HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
     </asp:GridView>