Tuesday, April 20, 2010

Sort Sorting GridView control Manually in Asp.net C#




Please visit my new Web Site https://coderstechzone.com



Asp.net SqlDataSource control ease our lives because if you are using SqlDataSource control to bind a GridView control then no need to sorting gridview or paging gridview control since you will achieve it automatically. But if you are using different datasource like Datatable, DataSet then you need to GridView sorting manually. Here in this article I will show you how you can develop GridView Sorting easily. One thing keep in mind that When you need to sort a GridView then each time you have to bind the GridView with data.

So you have two way to hold data:
1. You can read data from database each time
2. You can store data within viewstate or cache

Here I am using asp.net cache since you knew that viewstate will increase the page response time. Ok lets start. Add a page in your project then add a GridView on it. Now from GridView properties set the AllowSorting=true. Now in your each bind column set the sortexpression like below:
<asp:GridView ID="GridView1" runat="server" Width="800px" AutoGenerateColumns="False" AllowSorting="true" OnSorting="GridView1_Sorting" >
         <HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
         <RowStyle BackColor="LightGray" />
         <AlternatingRowStyle BackColor="LightGray" />
         <Columns>
             <asp:BoundField DataField="Brand" HeaderText="Brand Name" SortExpression="Brand"/>
             <asp:BoundField DataField="Category" HeaderText="Category Name" SortExpression="Category" />
             <asp:BoundField DataField="Product" HeaderText="Product Name" SortExpression="Product"/>
         </Columns>
        </asp:GridView>
* SortExpression must be same as DataField property.


Now in page_load method follow my below sample code:
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataTable dt;
            String SQL = "SELECT B.Name Brand,C.Name Category, " +
                    "P.Name Product FROM " +
                    "Brand B, Category C, Product P " +
                    "WHERE B.ID=P.BrandID AND C.ID=P.CategoryID Order BY 1,2,3";


            string sConstr = ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(sConstr))
            {
                using (SqlCommand comm = new SqlCommand(SQL, conn))
                {
                    conn.Open();
                    using (SqlDataAdapter da = new SqlDataAdapter(comm))
                    {
                        dt = new DataTable("tbl");
                        da.Fill(dt);
                    }
                }
            }

            GridView1.DataSource = dt;
            GridView1.DataBind();
            Cache["dt"] = dt;
            ViewState["Column_Name"] = "Brand";
            ViewState["Sort_Order"] = "ASC";
        }
    }

From here you can change your query according to your base table. Now add the Sorting event of your gridview and write the below code:
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression == ViewState["Column_Name"].ToString())
        {
            if (ViewState["Sort_Order"].ToString() == "ASC")
                RebindData(e.SortExpression, "DESC");
            else
                RebindData(e.SortExpression, "ASC");
        }
        else
            RebindData(e.SortExpression, "ASC");
    }
If you look at the code you found that here I am using a method named RebindData. The code for this method is given below:
private void RebindData(string sColimnName,string sSortOrder)
    {
        DataTable dt=(DataTable)Cache["dt"];
        dt.DefaultView.Sort = sColimnName + " " + sSortOrder;
        GridView1.DataSource = dt;
        GridView1.DataBind();
        ViewState["Column_Name"] = sColimnName;
        ViewState["Sort_Order"] = sSortOrder;
    }

Code Explanation:
Here if you look at my bind query in page_load event then you found that Brand column already sorted in ascending order thats why I have stored the Brand column name & sortorder, so that if user click again on Brand column then i need to sort the column in descending order but if user click on other column then i need to sort that column in ascending order. Hope now you can understand the logic why I use two viewstate variables ViewState["Column_Name"] and ViewState["Sort_Order"]. Basically those two variables is used to remeber user last action.

Now its your turn to make a generic sorting class for your project.

3 comments:

Anonymous said...

I get an error in this line
dt.DefaultView.Sort = sColimnName + " " + sSortOrder;

error : System.NullReferenceException: Object reference not set to an instance of an object.

please help

mooremediaone said...

Good post, the code worked for me. Got all my columns sorting. THANKS!

Unknown said...

Thanks lot.. working correctly...

Want to say something?
I WOULD BE DELIGHTED TO HEAR FROM YOU

Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Asp.net
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
     
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash