In the last article I talked about that how you can sort the Sort GridView Columns Manually with the Auto-Generate Columns property set to true. In this article I will demonstrate that how you can sort the Bound Columns. I will dynamically inject the script to the GridView column headers which will enable sorting.

Introduction:

In the last article I talked about that how you can sort the Sort GridView Columns Manually with the Auto-Generate Columns property set to true. In this article I will demonstrate that how you can sort the Bound Columns. I will dynamically inject the script to the GridView column headers which will enable sorting.

The Code:

I must admit that 95% of the total code is same as in my last article Sort GridView Columns Manually. For that reason I will only put the code which you have to add in order to have the GridView sorting work on the bound columns.

GridView_RowDataBound Event:

We are going to attach the client side postback to the GridView column headers. The best place to do this is inside the GridView_RowDataBound event which is fired whenever a row is bound in the GridView control. Let's take a look at the GridView_RowDataBound event.

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

{

if (e.Row.RowType == DataControlRowType.Header)

{

TableCellCollection cells = e.Row.Cells;

foreach (TableCell cell in cells)

{

cell.Text = Server.HtmlDecode(GenerateScript(GridView1.UniqueID, cell.Text)); }}}

The code is similar to what I have already discussed in my previous article. The new method "GenerateScript" has been included which will add the sorting feature to the column headers.

private string GenerateScript(string columnName,GridView gv)
{
string optionalParam = "Sort$" + columnName;

StringBuilder sb = new StringBuilder();
sb.Append("<a href=\"");
sb.Append("javascript:");
sb.Append(ClientScript.GetPostBackEventReference
(gv, optionalParam,false));
sb.Append("\">");
sb.Append(columnName);
sb.Append("</a>");

return sb.ToString();

}

As, you can see that I am attaching the column name with the "Sort$" which is the event argument generated which you click on the header of the GridView column. Apart from that I am also developing the links using a simple href links tags. The method ClientScript.GetPostBackEventReference injects the client side script that causes the postback and also gets the reference of the control that causes the postback. The control in this case will be the GridView control.

And that is pretty much it. I have also blogged about this scenario which you can view at this link.

I hope you liked the article, happy coding!