11 January 2016

How to create a scrollable table with header

See below example.  The tricks are 

Use jQuery to unhide the right column in the table when scroll bar is not visible.

Scrollbar is only visible if the row height * number of rows > table height

   table { 
     table-layout: fixed; 
   } 

is important to control the layout



 @model C2.Models.dtSalary  
 <!doctype html>  
 @{  
   Layout = null;  
 }  
 <script src="~/Scripts/jquery-1.10.2.js"></script>  
 <STYLE type="text/css">  
   table {  
     table-layout: fixed;  
   }  
   .TableDiv {  
     overflow: auto;  
     height: 400px;  
     width: 320px;  
   }  
   .TableHeaderDiv {  
     width: 320px;  
   }  
   .TableFormat {  
     font-family: Arial;  
     font-size: 0.8em;  
     text-align: center;  
     border-collapse: collapse;  
     width: 100%;  
   }  
   .MediumColumn {  
     width: 100px;  
   }  
   .LongColumn {  
     width: 200px;  
   }  
   .TdHeight {  
     height: 20px;  
   }  
   th {  
     font-weight: 600;  
   }  
   .ColumnNoDisplay {  
     width: 17px;  
     display: none;  
   }  
 </STYLE>  
 <div class="TableHeaderDiv">  
   <table border="1" cellpadding="1" cellspacing="0" class="TableFormat">  
     <colgroup>  
       <col class="MediumColumn" />  
       <col class="MediumColumn" />  
       <col class="MediumColumn" />  
       <col width="17px" />  
     </colgroup>  
     <tr>  
       <th>  
         IP Address  
       </th>  
       <th>  
         Country Name  
       </th>  
       <th>  
         City  
       </th>  
       <th></th>  
     </tr>  
   </table>  
 </div>  
 <div class="TableDiv">  
   <table border="1" cellpadding="1" cellspacing="0" class="TableFormat">  
     <colgroup>  
       <col class="MediumColumn" />  
       <col class="MediumColumn" />  
       <col class="MediumColumn" />  
       <col class="ColumnNoDisplay" />  
     </colgroup>  
     @foreach (var item in Model.salaryData)  
     {  
       <tr>  
         <td class="TableCell">  
           @Html.DisplayFor(modelItem => item.IPAddress)  
         </td>  
         <td class="TableCell">  
           @Html.DisplayFor(modelItem => item.CountryName)  
         </td>  
         <td class="TableCell">  
           @Html.DisplayFor(modelItem => item.City)  
         </td>  
         <td class="ColumnNoDisplay">&nbsp</td>  
       </tr>  
     }  
   </table>  
 </div>  
 <script>  
   var divHeight = 400  
   var rowHeight = 20  
   var rowcount = @Model.salaryData.Count;  
   if (rowcount * rowHeight > divHeight)  
   {  
   }  
   else  
   {  
     $(".ColumnNoDisplay").css('display','table-column');  
   }  
 </script>  

No comments:

Post a Comment