Manually Sorting DataBound GridView Columns

You can also sort DataBound columns of the GridView. The one thing that you need to do is to make the header columns as the links and write the client side scripts which will handle the client postbacks. Check out the code below.

 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
                (cell.Text,GridView1));
            }
        }
    }

 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();         

    }
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {

// Handle this event like I did in the previous post.

    }
    
protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
    {

        
if (e.Row.RowType == DataControlRowType.Header)
        {
            TableCellCollection cells = e.Row.Cells;

            
foreach (TableCell cell in cells)
            {
                GenerateScript(cell.Text, GridView1);
            }
        }
       
    }

As, you can see in the above code that I have made use of the ClientScript.GetPostBackEventReference method. You can also manually type the JavaScript __doPostBack method if you want. Something like this:

 private string GenerateScript(string id,string columnName)
    {
        StringBuilder sb = 
new StringBuilder(); 
        sb.Append("<a href=\"");
        sb.Append("javascript:__doPostBack('");
        sb.Append(id);
        sb.Append("','Sort$");
        sb.Append(columnName);
        sb.Append("')\">");
        sb.Append(columnName);
        sb.Append("</a>"); 
        
        
return sb.ToString();         
    }
Hope it helps!

 

powered by IMHO 1.3

Print | posted @ Friday, April 28, 2006 12:25 AM

Twitter