Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Datagrid: Matching header widths to column widths

ASP.NET Forum General Use

Datagrid: Matching header widths to column widths

by  dpdoug  Posted    (Edited  )
I use scrolling datagrids very frequently so I need to make the a custom header to be independent from the datagrid. The problem is getting the widths of header columns the same as the DataItem column widths.

The problem is that depending on what data is filtered into the grid, the widths of the grid can vary and the header widths not. I have mainly just made a close estimate in percentages and the columns usually more or less line up. But it's a lot of work guessing and trying till I finally get columns more or less lined up.

But I found a way to get around this problem:

Use fixed width columns and headers.

This will not work in every case since some columns could vary greatly, but even then the cells could be configured to wrap if the length is longer than the fixed width of the cell.

1) After you have built your scrolling grid and header, run it to see what the widths of the dataItem columns will be like.

2) Take a ruler with milimeters on it. Measure each column width and multiply the milimeters by 3. This will give you the width of the columns in pixels for each column header.

- Be sure to add an extra header cell to compensate for the area reserved for the scroll bar.

- The total of the header cell widths should be the same as the width of the grid plus the area reserved for the scroll bar.

<TH width="132px"><A class=sorthead onclick="SetSource('u.LastAction')" href="#" >Last Action</A></TH>

3) Set the width of each column in pixels in the ItemStyle tag of the DataGrid to the same width as the column header width:

<ItemStyle HorizontalAlign="Left" Width="132px">
</ItemStyle>

4) The last thing to do is turn off the header to the DataGrid:

<asp:DataGrid
id="grdUserTracking"
ShowHeader="False"
....
AutoGenerateColumns="False">

NOTE: If you have any columns that could possibly vary greatly in width set Wrap to true. Fields like dates, phone numbers and some types of numbers are likely to always be the same width. But if there are some numbers that could possibly get real long, you don't want to wrap those, so make sure those are wide enough to accomodate.

I noticed the other day that someone had a question about this, so I believe that this tip may benefit a few others also. I've been benefitted greatly from these forums, so I hope to be giving back something to help others.

happy programming!

dpdoug
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top