How to make the grid header fixed ( Freeze Header ) and fill data from a datatable

Home ASP.Net & C#
MVC
Interview Questions & Answers
Others


How to make the grid header fixed ( Freeze Header ) and fill data from a datatable


In my last post I have explained how to make the grid header fixed. If you did not see the post, you can check that here.
Now there is another requirement that we need to bind the data from the datatable or from database table or from some xml data source. When we are using grid view control, we can specify the datasource and bind the data to the grid. In our grid also we can do the same. It is very simple. In my opinion it is much faster than binding the datasource to the grid. 
To do this we need to add the following html code  

Step 1.
Copy and paste the following html codes into your .aspx or html page.

<div>
    <div id="divHeader" style="background-color:#ccc;" >
        <table class='gridstyle'>
            <tr style='height:43px; ' class='clsTableHeader' >
                <td class="ClsProduct1" >Product Name</td>
                <td class="ClsProduct1" >Product Code</td>
                <td class="ClsProduct1" >Product Type</td>
                <td class="ClsProduct1" >Price</td>
                <td class="ClsProduct2" >Number</td>
            </tr>
        </table>
    </div>
    <div id="divContent" runat="server" style="height:250px;overflow:auto;" >
        
    </div>
    </div>

 Step 2 
Copy and paste the style also.


<style type="text/css">

.gridstyle

{

    border:none;
    border-collapse:collapse;
    border-right:none;
    font-familyTahoma, Arial, Verdana;
    font-size11px;
    text-align:left;
    width100%;
    min-width:400px;
}
.gridstyleBody
{
    border:none;
    border-collapse:collapse;
    border-right:none;
    font-familyTahoma, Arial, Verdana;
    font-size11px;
    text-align:left;
    width100%;
    min-width:400px;
}

.ClsProduct1
{
    border:1px solid #FFFFFF;
    width20%;
    font-weight:bold;
    text-align:center;
}
.ClsProduct2
{
    border:1px solid #FFFFFF;
    font-weight:bold;
    text-align:center;   
}

</style>

We need to add the following script reference also. This piece of script checks whether we need to add a padding to the right side. In some cases, if there is no scrolls ( only few rows of data ), we do not need to add a padding to the header. We are doing this only for not having any design issues. 

 Step 3

<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>
 <script type="text/javascript">
        $(document).ready(function () {
            checkScroll();
        });
        function checkScroll() {
            var element = document.getElementById('divContent');
            if (element.scrollHeight > element.clientHeight) {
                $('#divHeader').css('padding-right', '18px');
            }
            else {
                $('#divHeader').css('padding-right', '0px');
            }
        }
    </script>


 Step 4

Now, we need to add the code for binding the datatable to this grid. On the page load event, I have a datatable dt with 50 records in it. I am just creating a table structure from the C# code and binding it to the grid as innerHTML of the our second div ( divContent) . It is very easy for you to make it possible. Just copy and paste the following code into the page load event of the page.


        DataTable dt = new DataTable();
        // You can add your connection details  here
        //************
        //SqlConnection conn = new SqlConnection(" your connection string ");
        //SqlCommand cmd = new SqlCommand();
        //cmd.CommandText = " select * from product where deleted = 0";
        //cmd.Connection = conn;
        //conn.Open();
        //SqlDataAdapter ada = new SqlDataAdapter(cmd);
        //ada.Fill(dt);
        //conn.Close();
        //************

        string strMyTable = "";
        string strStyle = "";
        string strStyle1 = "'height:43px;background-color:#E4F5FC; '";
        string strStyle2 = "'height:43px;background-color:#EFEFEF; '";
// I am just creating a data table with some rows. Bind it from the database or other sources as you want.
        dt.Columns.Add("ProductName");
        dt.Columns.Add("ProductCode");
        dt.Columns.Add("ProductType");
        dt.Columns.Add("Price");
        dt.Columns.Add("Number");

        for (int i = 0; i < 50; i++)
        {
            dt.Rows.Add();
            dt.Rows[i]["ProductName"] = "Product Name " + (i + 1).ToString();
            dt.Rows[i]["ProductCode"] = "Product Code " + (i + 1).ToString();
            dt.Rows[i]["ProductType"] = "Product Type " + (i + 1).ToString();
            dt.Rows[i]["Price"] = "Price " + (i + 1).ToString();
            dt.Rows[i]["Number"] = "Number " + (i + 1).ToString();
        }
// Created a datatable with 50 records in it.
// Create the html table structure dynamically from the data table. 
        strMyTable = "  <table class='gridstyleBody'>";
        if (dt.Rows.Count > 0)
        {
            for (int k = 0; k < dt.Rows.Count; k++)
            {
                if (k % 2 == 0)
                {
                    strStyle = strStyle1;
                }
                else
                {
                    strStyle = strStyle2;
                }
                strMyTable += "<tr style=" + strStyle + " class='clsTableHeader' >";
                strMyTable += "<td class='ClsProduct1' style='font-weight:normal;text-align:left;'>" + dt.Rows[k]["ProductName"].ToString() + "</td>";
                strMyTable += "<td class='ClsProduct1' style='font-weight:normal;text-align:left;'>" + dt.Rows[k]["ProductCode"].ToString() + "</td>";
                strMyTable += "<td class='ClsProduct1' style='font-weight:normal;text-align:left;'>" + dt.Rows[k]["ProductType"].ToString() + "</td>";
                strMyTable += "<td class='ClsProduct1' style='font-weight:normal;text-align:left;'>" + dt.Rows[k]["Price"].ToString() + "</td>";
                strMyTable += "<td class='ClsProduct2' style='font-weight:normal;text-align:left;'>" + dt.Rows[k]["Number"].ToString() + "</td>";
                strMyTable += " </tr>";
            }
        }
        strMyTable += " </table> ";
// give it to the innerHTML of the div. 
        divContent.InnerHtml = strMyTable;
    }

Code explanation 

I am referring content for the area we need to make the scroll. 
Our grid structure is very simple. For the header we have a div and a table. You need to give the style as you want. Add the columns we needed in the table <td> s. Give the width of the columns as you want. It is better to give it in % ( not in pixel). So it will be easier to adjust with the window width. Also if you give class name and give the style in the class, it can be reused for the content area.
Now for our content area ( scrollable area ) we are using the same structure as header ( Else there will be design issues ). A div and one table. Please do not change this structure. We are dynamically creating the same table structure and style as our header table from the C# code. Now just give the dynamically created table as the innerHTML of our content div. Everything is completed now. 
One more thing we need to take care is- in some cases when the content area rows are only few( No scrolling ). In that cases we dont need a padding-right: 18px; to the header div. We are giving a padding-right: 18px; to the header div to adjust the scroll width with our content columns. So we need to check on the page load event of javascript to check whether we need to add the padding or not. I have done it in the script area. Please make sure that it is added in your columns also( Step 3). 
Now everything is complete. Please ask if you have any questions.

Thanks for reading my post. Have a nice day. :)

No comments:

Post a Comment