Highlight the column in Gridview after Sorting


In this article we will try to highlight a particular column after sorting is done. The coloring of columns is done on OnItemDataBound event in the gridview whereas sorting is done on OnSortCommand event.

In this basic article, our aim is to highlight the columns in gridview when we do Sorting. It will be more descriptive and user friendly if we provide colors to column when they are sorted.

The coloring of columns is done on OnItemDataBound event in the gridview whereas sorting is done on OnSortCommand event.

You can apply/extend your own logic while following this code flow. You can provide colors or change the font size and font type or you can even place the up/down arrows for sort columns.

Follow the step by step process below to achieve this:

On our .aspx page. Place the grid view.


asp:GridView id="gvDetails" OnItemDataBound ="ColorColumns" AllowSorting="True" OnSortCommand="DataSorting" runat="server"


Now on our code behind file. Bind the grid view and pass the course Id or your data key names

private void Page_Load(System.Object sender, System.EventArgs e)
{
//Bind the data grid on page load
if (!Page.IsPostBack) {
BindGridView("CourseID");
}
}

public void BindGridView(string colToSort)
{

ViewState("Sort") = colToSort;

//Fill the DataSet

DataView dvSort = ds.Tables(0).DefaultView;

dvSort.Sort = colToSort;

gvDetails.DataSource = dvSort;

gvDetails.DataBind();

}


This event will be called When the user sorts the particular column

protected void DataSorting(object source, System.Web.UI.WebControls.DataGridSortCommandEventArgs e)
{

BindGridView(e.SortExpression.ToString());

}




Now color the columns

protected void ColorColumns(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
{

DataView dv = gvDetails.DataSource;

DataColumnCollection dCol = dv.Table.Columns;

if (e.Item.ItemType == ListItemType.Header) {
if (!string.IsNullOrEmpty(ViewState("Sort"))) {

e.Item.Cells[dCol.IndexOf(dCol[ViewState("Sort")])].BackColor = Color.Orange;

e.Item.Cells[dCol.IndexOf(dCol[ViewState("Sort")])].ForeColor = Color.Aqua;

}

}

}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: