Attempting to align contents of GridView cells on ASP.NET Web Forms

Donald Symmons 2,946 Reputation points
2024-11-10T11:55:41.8966667+00:00

Hello,

I am attempting to align the contents of GridView cells on ASP.NET Web Forms, but I am encountering an issue where the GridView header is not aligning as expected. Here is how it looks in the image below

saved

What steps can be taken to resolve this, please?

Here is the code I have tried:

HTML

<asp:GridView ID="Gridview2" runat="server" CellPadding="10" RowStyle-Width="100%" RowStyle-CssClass="table" CssClass="table table-condensed" Font-Size="10pt" HeaderStyle-Width="100%" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Size="10pt" AutoGenerateColumns="False" Style="width: 100%; font-weight: 400;" RowStyle-Height="50px"
                                        BorderStyle="None" GridLines="None" Height="70px" HeaderStyle-Height="50px" HeaderStyle-BackColor="#F9FBFC" OnRowDataBound="Gridview2_RowDataBound">
                                        <Columns>
                                            <asp:BoundField DataField="Item" HeaderText="Item" />
                                            <asp:BoundField DataField="Qty" HeaderText="Quantity" />
                                            <asp:BoundField DataField="Rate" HeaderText="Price" />
                                            <asp:BoundField DataField="Amount" HeaderText="Amount" />
                                        </Columns>
                                        <HeaderStyle Height="35px" />
                                    </asp:GridView>

C#

protected void Page_Load(object sender, EventArgs e)
        {
            GetData();
        }
        private void GetData()
        {
            if (!this.IsPostBack)
            {
                DataTable dt = new DataTable();
                dt.Columns.AddRange(new DataColumn[4] {
                            new DataColumn("Item", typeof(string)),
                            new DataColumn("Qty", typeof(string)),
                            new DataColumn("Rate", typeof(string)),
                            new DataColumn("Amount",typeof(string)) });
                dt.Rows.Add("Flight Ticket", "1", "132,000.00", "132,000.00");
                dt.Rows.Add("Service Charge", "1", "3,000.00", "3,000.00");
                dt.Rows.Add("Online Fees", "1", "1,000.00", "1,000.00");
                Gridview2.DataSource = dt;
                Gridview2.DataBind();
            }
        }

protected void Gridview1_RowDataBound (object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                e.Row.Cells[1].HorizontalAlign = HorizontalAlign.Center;
                e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Right;
                e.Row.Cells[3].HorizontalAlign = HorizontalAlign.Right;
            }
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                e.Row.Cells[1].HorizontalAlign = HorizontalAlign.Center;
                e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Right;
                e.Row.Cells[3].HorizontalAlign = HorizontalAlign.Right;
            }
        }

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,945 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,520 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,053 questions
{count} votes

Accepted answer
  1. Albert Kallal 5,331 Reputation points
    2024-11-19T21:42:16+00:00

    Ok, a few things:

    First up, it is clear that you are using bootstrap classes here to format the GridView. (this needs to be pointed out). What occurs then is you are using server code to "try" and set the alignment of the GridView controls (with server side code), and then once the content is rendered, created, and then set to the client side, you ALSO specified some bootstrap classes to THEN format the GridView for you, and that's of course going to override your original settings. More important, you using the GridView formatting attribuotes (such as HorizontalAlign.Right), and that again is not really css, but server side code to spit out some formatted text. Of course, as we all see, THEN specifying a bunch of css classes (from bootstrap) overrides any work we done.

    So, it not really JUST adding some references to bootstrap + css that causing the issues here, but that of ALSO specifying the bootstrap table classes here (such as CssClass="table table-condensed" .

    Hence, in this example, it looks like boatloads of efforts been made using GridView formatting, and then an whole new extra round of efforts been made using css, which of course is contradicting and overrides all the boatloads of settings you have in code and markup.

    However, since css is "cumulative", then I would suggest you attempt to style the columns (alignment) using css, and not the built in GV attributes, since css is going to override such settings anyway.

    And since you ARE letting css (table class) to style the GridView (which is really nice, and it also makes the GV responsive for the most part), then I suggest removing all (most) of the GridView formatting you have - it just really not needed, and you can thus clean up the markup you have by boatloads here. No use to have two systems fighting each other - it just going to make formatting kind of "jinky" and not reliable.

    So, then, change the formatting using css like this:

            protected void Gridview2_RowDataBound(object sender, GridViewRowEventArgs e)
            {
                if (e.Row.RowType == DataControlRowType.Header)
                {
                    // e.Row.Cells[1].HorizontalAlign = HorizontalAlign.Center;
                    e.Row.Cells[1].Style.Add("text-align", "right");
                    e.Row.Cells[2].Style.Add("text-align", "right");
                    e.Row.Cells[3].Style.Add("text-align", "right");
                }
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    e.Row.Cells[1].Style.Add("text-align", "right");
                    e.Row.Cells[2].Style.Add("text-align", "right");
                    e.Row.Cells[3].Style.Add("text-align", "right");
                }
            }
    
    

    And the result is this:

    User's image

    Also, since bootstrap does such a good job, then I suggest getting rid of all of the "attempted" formatting (since the css overwrites those settings anyway. Hence you only really need this:

                <style>
                    th {
                        background-color: lightgray!important;
    } 
                </style>
    
                <asp:GridView ID="Gridview2" runat="server"                  
                    CssClass="table table-condensed" 
                    AutoGenerateColumns="False"
                    width="100%"
                    OnRowDataBound="Gridview2_RowDataBound" >
                    <Columns>
                        <asp:BoundField DataField="Item" HeaderText="Item"  />
                        <asp:BoundField DataField="Qty" HeaderText="Quantity" />
                        <asp:BoundField DataField="Rate" HeaderText="Price" />
                        <asp:BoundField DataField="Amount" HeaderText="Amount" />
                    </Columns>
                    <HeaderStyle Height="35px" />
                </asp:GridView>
    
    

    And now we get this:

    User's image

    So, HUGE reduction in the markup. And adjust the light grey for the heading if you want something lighter, but all those settings were being overwritten by css anyway, and thus are not required. In fact, even in above, the HeaderStyle tag should be removed (but editing of this post for some reason is not working!).


3 additional answers

Sort by: Most helpful
  1. AgaveJoe 28,541 Reputation points
    2024-11-10T13:37:35.74+00:00

    Maybe there is a mistake in my code, that I am yet to see

    The markup handler name "OnRowDataBound="Gridview2_RowDataBound"" does not match the actual C# handler named "Gridview1_RowDataBound". Please use the Visual Studio debugger to verify the logic flow.

    I would use template fields to control the individual column styles in the markup using standard CSS rather than code the behind.


  2. Lan Huang-MSFT 29,911 Reputation points Microsoft Vendor
    2024-11-11T02:09:01.3166667+00:00

    Hi @Donald Symmons,

    About the markup handler name, that's a mistake I did.

    After this modification it should work fine, right?

    Below is my test.

     <asp:GridView ID="Gridview2" runat="server" CellPadding="10" RowStyle-Width="100%" RowStyle-CssClass="table" CssClass="table table-condensed" Font-Size="10pt" HeaderStyle-Width="100%" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Size="10pt" AutoGenerateColumns="False" Style="width: 100%; font-weight: 400;" RowStyle-Height="50px"
         BorderStyle="None" GridLines="None" Height="70px" HeaderStyle-Height="50px" HeaderStyle-BackColor="#F9FBFC" OnRowDataBound="Gridview2_RowDataBound">
         <Columns>
             <asp:BoundField DataField="Item" HeaderText="Item" />
             <asp:BoundField DataField="Qty" HeaderText="Quantity" />
             <asp:BoundField DataField="Rate" HeaderText="Price" />
             <asp:BoundField DataField="Amount" HeaderText="Amount" />
         </Columns>
         <HeaderStyle Height="35px" />
     </asp:GridView>
    
     protected void Page_Load(object sender, EventArgs e)
     {
         GetData();
     }
     private void GetData()
     {
         if (!this.IsPostBack)
         {
             DataTable dt = new DataTable();
             dt.Columns.AddRange(new DataColumn[4] {
                         new DataColumn("Item", typeof(string)),
                         new DataColumn("Qty", typeof(string)),
                         new DataColumn("Rate", typeof(string)),
                         new DataColumn("Amount",typeof(string)) });
             dt.Rows.Add("Flight Ticket", "1", "132,000.00", "132,000.00");
             dt.Rows.Add("Service Charge", "1", "3,000.00", "3,000.00");
             dt.Rows.Add("Online Fees", "1", "1,000.00", "1,000.00");
             Gridview2.DataSource = dt;
             Gridview2.DataBind();
         }
     }
     protected void Gridview2_RowDataBound(object sender, GridViewRowEventArgs e)
     {
         if (e.Row.RowType == DataControlRowType.Header)
         {
             e.Row.Cells[0].HorizontalAlign = HorizontalAlign.Left;
             e.Row.Cells[1].HorizontalAlign = HorizontalAlign.Center;
             e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Right;
             e.Row.Cells[3].HorizontalAlign = HorizontalAlign.Right;
         }
         if (e.Row.RowType == DataControlRowType.DataRow)
         {
             e.Row.Cells[0].HorizontalAlign = HorizontalAlign.Left;
             e.Row.Cells[1].HorizontalAlign = HorizontalAlign.Center;
             e.Row.Cells[2].HorizontalAlign = HorizontalAlign.Right;
             e.Row.Cells[3].HorizontalAlign = HorizontalAlign.Right;
         }
     }
    

    User's image

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread


  3. SurferOnWww 3,276 Reputation points
    2024-11-11T02:22:41.9166667+00:00

    I suggest not using the event handler such as Gridview1_RowDataBound shown.

    Instead, please try using the designer of Visual Studio to set the styles to the columns of GridView as shown below:

    GridView2

    The resultant .aspx is shown below:

    <%@ Page Language="C#" AutoEventWireup="true" 
        CodeBehind="WebForm49.aspx.cs" Inherits="WebForms1.WebForm49" %>
    
    <!DOCTYPE html>
    
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
        <title></title>
    </head>
    <body>
        <form id="form1" runat="server">
            <asp:GridView ID="GridView2" 
                runat="server" 
                AutoGenerateColumns="False" 
                CellPadding="10" 
                GridLines="Horizontal" 
                BorderStyle="None">
                <Columns>
                    <asp:BoundField DataField="Item" HeaderText="Item" />
                    <asp:BoundField DataField="Qty" HeaderText="Quantity" >
                    <ItemStyle HorizontalAlign="Right" />
                    </asp:BoundField>
                    <asp:BoundField DataField="Rate" HeaderText="Price" >
                    <ItemStyle HorizontalAlign="Right" />
                    </asp:BoundField>
                    <asp:BoundField DataField="Amount" HeaderText="Amount" >
                    <ItemStyle HorizontalAlign="Right" />
                    </asp:BoundField>
                </Columns>
                <HeaderStyle BackColor="#F9FBFC" />
            </asp:GridView>
        </form>
    </body>
    </html>
    

    The above shows the GridView on browser as follows:

    GridView3


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.