Sunday, September 4, 2011

GridView Header Issue

 
If you have worked with the ASP.NET GridView you may notice an odd problem relating to the header text alignment. If you set the grid’s HeaderStyle.HorizontalAlign property to Left the headers will appear left aligned in Chrome, Firefox and older versions of IE (as well as IE compatibility mode), but in later version of IE the header text will stay centered instead of left aligned. Here is the HTML that comes from the GridView:

<table cellspacing="0" rules="all" border="1" id="GridView1" style="width:50%;border-collapse:collapse;">     
    <tr align="left">                
        <th scope="col">Field1</th>
        <th scope="col">Field2</th>
        <th scope="col">Field3</th>        
    </tr>         
    <tr>               
        <td>Data1</td>
        <td>Data2</td>
        <td>Data3</td>        
    </tr> 
</table>

The reason for this alignment problem is the align attribute on the <tr> element. In the later version of IE this alignment is not inherited by the <th> elements like it is in other browsers. I have been doing some reading on this issue and there seems to be some debate as to whether this is what the HTML specification intended or not. I will leave that debate to others and just show how to resolve the problem.
If you are not auto generating the columns you can fix this by setting the HeaderStyle.HorizontalAlign property to the appropriate value for each of your columns. So in this example I would set them to Left. The GridView will now output the following HTML:

<table cellspacing="0" rules="all" border="1" id="GridView1" style="width:50%;border-collapse:collapse;">
    <tr align="left">                
        <th align="left" scope="col">Field1</th>
        <th align="left" scope="col">Field2</th>
        <th align="left" scope="col">Field3</th>         
    </tr>
    <tr>
        <td>Data1</td>
        <td>Data2</td>
        <td>Data3</td>
    </tr>
</table>


You will see that each <th> element now has an align attribute which will work the same in any browser.


You also can achieve the same thing using CSS which has the advantage of working whether you are auto generating the columns or not. To do this first add this style to either the header of your page, or to a CSS file:


<style type="text/css"> 
    .gvclass table th {text-align:left;} 
</style> 

Then wrap your GridView in a div tag that uses the .gvclass:

<div class="gvclass"> 
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="50%"> 
    </asp:GridView> 
</div>

5 comments:

VATANSEVER said...

thanks so much

VATANSEVER said...

thanks so much

VATANSEVER said...

thanks so much

Debarupa said...

Thank you so very much!!

I was having a hard time finding a solution to this problem.

Thanks again!!

Krishna kumar said...

Thank you...It worked