Programming in almost language

Thi s is the site where you may share your knowledge and experience to eachother..

Archive for February 15th, 2008

Sorting DataGrid

Posted by Praveen Kumar on February 15, 2008

 We all know that GridView columns can be sorted automatically when SQLDataSource is being used. But what if you are not using SqlDataSource to populate the GridView. Sorting the GridView manually is pretty straight forward task take a look at the code below. private const string ASCENDING = ” ASC”;
 
private const string DESCENDING = ” DESC”;

 public SortDirection GridViewSortDirection
    {
        
get
        
{
            
if (ViewState["sortDirection"] == null)
                ViewState["sortDirection"] = SortDirection.Ascending;

            return (SortDirection) ViewState["sortDirection"];                
        }
        
set { ViewState["sortDirection"] = value; } 
    }

    protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        
string sortExpression = e.SortExpression;

        if (GridViewSortDirection == SortDirection.Ascending)
        {
            GridViewSortDirection = SortDirection.Descending;
            SortGridView(sortExpression, DESCENDING);
        }
        
else
        
{
            GridViewSortDirection = SortDirection.Ascending;
            SortGridView(sortExpression, ASCENDING); 
        }   
       
    }

    private void SortGridView(string sortExpression,string direction)
    {
        
//  You can cache the DataTable for improving performance
        
DataTable dt = GetData().Tables[0]; 

        DataView dv = new DataView(dt); 
        dv.Sort = sortExpression + direction;         

        GridView1.DataSource = dv;
        GridView1.DataBind();         
    }

Posted in DATAGRID AND GRIDVIEW | Leave a Comment »