Introduction
In this article I will explain how to highlight or select the column of an ASP.NET GridView control whose header has been clicked for sorting.
Step 1: Create a new ASP.NET Web Application and drag a GridView control on Default.aspx from the Toolbox. And enable Paging and Sorting as discussed in my previous articles (GridView Paging and Sorting in ASP.NET using SqlDataSource or GridView Paging and Sorting in ASP.NET without using a DataSource)
Step 2: Write the following in the RowDataBound event of the GridView to highlight the header of the column that has been clicked for sorting:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
LinkButton lnkbtn;
if (e.Row.RowType == DataControlRowType.Header)
{
foreach (TableCell cell in e.Row.Cells)
{
lnkbtn = (LinkButton)cell.Controls[0];
if (!string.IsNullOrEmpty(GridView1.SortExpression))
{
if (GridView1.SortExpression.Equals(lnkbtn.Text))
{
cell.BackColor = System.Drawing.Color.Crimson;
}
}
}
}
}
The GridView RowDataBound event is fired when a row of the GridView has been filled with data. It is fired for every row of the GridView including its header and footer.
Here first we check if the current row is a header row by checking the RowType property. Then we loop through all the cells in the header row. Each cell is cast in a LinkButton control as when sorting has been enabled, the headers of the GridView turns into a LinkButton control. Then we check if the GridView column header has been clicked for sorting using the GridView.SortExpression property. Then we set the background color of the cell whose text matches the SortExpression (the Column text that was clicked for sorting).
Step 3: Write the following code in the DataBound event of the GridView control to highlight the other rows of data of the sorted column:
protected void GridView1_DataBound(object sender, EventArgs e)
{
int sortedColumnPosition = 0;
LinkButton lnkbtn;
// Gets position of column whose header text matches SortExpression
// of the GridView when column is sorted
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
lnkbtn = (LinkButton)cell.Controls[0];
if (lnkbtn.Text == GridView1.SortExpression)
{
break;
}
sortedColumnPosition++;
}
if (!string.IsNullOrEmpty(GridView1.SortExpression))
{
foreach (GridViewRow row in GridView1.Rows)
{
row.Cells[sortedColumnPosition].BackColor = System.Drawing.Color.LavenderBlush;
}
}
}
The GridView DataBound event is fired when all the data is bound to the GridView.
Here, first we calculate the position of the sorted column. Then first we check if the GridView has been clicked for sorting using the GridView.SortExpression property, then we loop through rows of the GridView and set the background color of the cell at the sorted column position.
Output
When you sort the GridView by clicking on its header, then its header along with its data in each row will be highlight like in the following: