Skip to main content

How to Add a Locked Header Row to an ASP.NET GridView Control


How to Add a Locked Header Row to an ASP.NET GridView Control :

The GridView control is often used to display tabular data, much like an Excel spreadsheet. However, unlike Excel, the GridView control doesn't have any automatic way of locking the header row so that it doesn't scroll out of view.

Previously I was Explained about the How to remove rows from GridView using jQuery in asp.net,

Nested GridView in ASP.NET Using c# with show/hide .



Check out this example of a GridView within a DIV with the overflow-Y property set to scroll. Notice that as you scroll the GridView, the header row scrolls out of view. It would be more convenient to have a locked header row so that the header row is always visible regardless of the scoll position of the GridView. It would also be nice to have a header row that dynamically configured itself as per the data source so that if we add a new field to the GridView, a corresponding column automatically gets added to the locked header row.
Here's another example, but this time, the header row stays locked at the top of the GridView so that you can scroll without losing track of column names. There are a few steps required to implement this functionality.
  1. Create a DIV on the page to contain the header row and set the DIV (either statically or dynamically) to the same width as the DIV that contains the GridView.
  2. Insert an ASP.NET Table control into the header DIV.
  3. In Page_Init, dynamically add the necessary cells to the header table and set the appropriate properties so that it matches the appearance of the rest of the GridView.
  4. Check for sortable columns and dynamically add sorting LinkButtons to the header row.
  5. Add code to handle the LinkButton's Click event and sort appropriately.
Let's go through each of these steps. (If you'd prefer to work with a working project, you can download the project at the end of this post.)

Creating the Header DIV and Inserting an ASP.NET Table Control (Steps 1 and 2)

To create a locked header row, we need to disable the header for the GridView control and instead dynamically create our own header.
  1. Select the GridView control and change the ShowHeader property to false.
  2. Create a new DIV above the DIV containing the GridView control using the following code.
<!-- *** Begin Header Table *** -->
<div id="DivHeader" style="vertical-align:top;width:650px;">
    <asp:Table ID="HeaderTable" runat="server"
               CellPadding="4"
               CellSpacing="0"
               Font-Size="11pt"
               BackColor="#274511"
               ForeColor="White">
    </asp:Table>
</div>
<!-- *** End Header Table *** -->
Note that the properties for my Table control were derived from the theme applied to my sample page. You can set these properties as you wish or dynamically set them so that they adjust to the GridView's properties automatically.
Notice that this Table control doesn't contain any cells. We'll add the necessary cells in Page_Init in the next step.

Add Code to Page_Init to Dynamically Create Header Cells and LinkButtons (Steps 3 and 4)

To dynamically add the cells for the header table, add the following code to Page_Init.
protected void Page_Init(object sender, EventArgs e)
{
    TableRow headerRow = new TableRow();

    for (int x = 0; x < GridView1.Columns.Count; x++)
    {
        DataControlField col = GridView1.Columns[x];

        TableCell headerCell = new TableCell();
        headerCell.BorderStyle = BorderStyle.Solid;
        headerCell.BorderWidth = 1;
        headerCell.Font.Bold = true;

        // if the column has a SortExpression, we want to allow
        // sorting by that column. Therefore, we create a linkbutton
        // on those columns.
        if (col.SortExpression != "")
        {
            LinkButton lnkHeader = new LinkButton();
            lnkHeader.PostBackUrl = HttpContext.Current.Request.Url.LocalPath;
            lnkHeader.CommandArgument = col.SortExpression;
            lnkHeader.ForeColor = System.Drawing.Color.White;
            lnkHeader.Text = col.HeaderText;
            lnkHeader.Click += new EventHandler(HeaderLink_Click);
            headerCell.Controls.Add(lnkHeader);
        }
        else
        {
            headerCell.Text = col.HeaderText;
        }

        headerCell.Width = col.ItemStyle.Width;
        headerRow.Cells.Add(headerCell);

    }

    HeaderTable.Rows.Add(headerRow);
}
This code adds a new TableCell to the header table and then sets specific properties on that TableCell based on whether or not the GridView's column has a SortExpression specified. If it doesn't, this code just sets the Text property of the cell to the GridView column's HeaderText property. Otherwise, it creates a LinkButton and sets the following properties on it.
  • PostBackUrl - Set to the local URL of the current request.
  • CommandArgument - Set to the SortExpression of the GridView's column so that we can apply it when the LinkButton is clicked.
  • ForeColor - Set to White in my example, but you can set this dynamically if you wish to make the example more generic.
  • Text - Set to the GridView column's HeaderText property.
I also add a new event handler for the Click event of the LinkButton control. Let's look at the code for that event.

Code for the LinkButton's Click Event

The code in the LinkButton's Click event applies the necessary SortExpression based on which LinkButton was clicked. The code for the Click event appears below.
protected void HeaderLink_Click(object sender, System.EventArgs e)
{
    LinkButton lnkHeader = (LinkButton)sender;
    SortDirection direction = SortDirection.Ascending;

    // the CommandArgument of each linkbutton contains the sortexpression
    // for the column that was clicked.
    if (GridView1.SortExpression == lnkHeader.CommandArgument)
    {
        if (GridView1.SortDirection == SortDirection.Ascending)
        {
            direction = SortDirection.Descending;
        }
    }

    GridView1.Sort(lnkHeader.CommandArgument, direction);
}
This code checks the CommandArgument for the LinkButton that was clicked (retrieved from the EventArgs) and applies the ascending or descending SortDirection based upon the result. It then calls the Sort method on the GridView.

AJAX-Enabling the Sample

If you are using ASP.NET AJAX, the code as-is will not do a partial postback. In order to have the LinkButtons sort using an AJAX async postback, you need to replace the line of code that sets the PostBackUrl property of the LinkButton with the following code.
lnkHeader.ID = "Sort" + col.HeaderText;
Doing this will allow ASP.NET Viewstate to track the LinkButton so that ASP.NET AJAX will work with the LinkButton.
Using this example, you can easily apply a locked header row to your GridView controls. If you'd like the completed sample project, you can download it below.

Sample Project

Size: 12KB
Download Now


Comments

Popular posts from this blog

How to hide url parameters in asp.net

There are different ways to Hide the URL in asp.net , you can choose any one from bellow options . Previously I was Explained about the  Difference between Convert.tostring and .tostring() method Example  ,   Reasons to use Twitter Bootstrap , How to Register AJAX toolkit in web.config file in asp.net a) Using Post Method b) Using Of Session . c) URL Encoding & decoding process . d) Using Server.Transfer() instead of Response.Redirect() method (1)Use a form and POST the information. This might require additional code in source pages, but should not require logic changes in the target pages (merely change Request.QueryString to Request.Form). While POST is not impossible to muck with, it's certainly less appealing than playing with QueryString parameters. (2)Use session variables to carry information from page to page. This is likely a more substantial effort compared to (1), because you will need to take session variable checking into account...

How to send mail asynchronously in asp.net with MailMessage

With Microsoft.NET Framework 2.0 everything is asynchronous and we can send mail also asynchronously. This features is very useful when you send lots of bulk mails like offers , Discounts , Greetings . You don’t have to wait for response from mail server and you can do other task . By using     SmtpClient . SendAsync Method (MailMessage, Object)    you need to do  System.Net.Mail has also added asynchronous support for sending email. To send asynchronously, you need need to Wire up a SendCompleted event Create the SendCompleted event Call SmtpClient.SendAsync smtpClient.send() will initiate the sending on the main/ui  thread and would block.  smtpClient.SendAsync() will pick a thread from the .NET Thread Pool and execute the method on that thread. So your main UI will not hang or block . Let's create a simple example to send mail. For sending mail asynchronously you need to create a event handler that will notify that mail success...

12 Sentences that Change Your Attitude at Work

If you work with the right attitude and right way, you’ll have your productivity up another level, and eventually, success will be just a step away. These are the 12 encouraging sentences that could change your attitude at work. #1 Don’t work harder, work deeper. #2 When you are young, work to learn, not to earn. #3 If you work really hard and are kind, amazing things will happen. #4 Productivity is never an accident. It is always the result of commitment to excellence, intelligent planning, and focused effort. #5 Most people work just hard enough not to get fired and get paid just enough money not to quit. #6 Boost your productivity by taking action immediately after setting a target even without perfect plans. Adjust your course along the way. #7 To be successful, the first thing to do is to fall in love with your work. #8 Identify your peak hour of productivity. Schedule your most important task for this period. Work on unimportant tasks during non-peak hours. #9 Be a mo...