Skip to main content

grid searching

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:
01<asp:GridView ID="GridView1" runat="server" Width="800px" AutoGenerateColumns="False" AllowSorting="true" OnSorting="GridView1_Sorting" >
02         <HeaderStyle BackColor="Red" Font-Bold="true" ForeColor="White" />
03         <RowStyle BackColor="LightGray" />
04         <AlternatingRowStyle BackColor="LightGray" />
05         <Columns>
06             <asp:BoundField DataField="Brand" HeaderText="Brand Name" SortExpression="Brand"/>
07             <asp:BoundField DataField="Category" HeaderText="Category Name" SortExpression="Category" />
08             <asp:BoundField DataField="Product" HeaderText="Product Name" SortExpression="Product"/>
09         </Columns>
10        </asp:GridView>
* SortExpression must be same as DataField property.


Now in page_load method follow my below sample code:
01protected void Page_Load(object sender, EventArgs e)
02    {
03        if (!IsPostBack)
04        {
05            DataTable dt;
06            String SQL = "SELECT B.Name Brand,C.Name Category, " +
07                    "P.Name Product FROM " +
08                    "Brand B, Category C, Product P " +
09                    "WHERE B.ID=P.BrandID AND C.ID=P.CategoryID Order BY 1,2,3";
10 
11 
12            string sConstr = ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString;
13            using (SqlConnection conn = new SqlConnection(sConstr))
14            {
15                using (SqlCommand comm = new SqlCommand(SQL, conn))
16                {
17                    conn.Open();
18                    using (SqlDataAdapter da = new SqlDataAdapter(comm))
19                    {
20                        dt = new DataTable("tbl");
21                        da.Fill(dt);
22                    }
23                }
24            }
25 
26            GridView1.DataSource = dt;
27            GridView1.DataBind();
28            Cache["dt"] = dt;
29            ViewState["Column_Name"] = "Brand";
30            ViewState["Sort_Order"] = "ASC";
31        }
32    }

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:
01protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
02    {
03        if (e.SortExpression == ViewState["Column_Name"].ToString())
04        {
05            if (ViewState["Sort_Order"].ToString() == "ASC")
06                RebindData(e.SortExpression, "DESC");
07            else
08                RebindData(e.SortExpression, "ASC");
09        }
10        else
11            RebindData(e.SortExpression, "ASC");
12    }
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:
1private void RebindData(string sColimnName,string sSortOrder)
2    {
3        DataTable dt=(DataTable)Cache["dt"];
4        dt.DefaultView.Sort = sColimnName + " " + sSortOrder;
5        GridView1.DataSource = dt;
6        GridView1.DataBind();
7        ViewState["Column_Name"] = sColimnName;
8        ViewState["Sort_Order"] = sSortOrder;
9    }

Comments

Popular posts from this blog

Editing Child GridView in Nested GridView

Editing Child GridView in Nested GridView In this article we will explore how to edit child gridview in the nested gridview.   Let''s write some code. Step 1:  Add scriptmanager in the aspx page. < asp : ScriptManager   ID ="ScriptManager1"   runat ="server"   EnablePageMethods ="true"> </ asp : ScriptManager > Step 2:  Add below stylesheet for modal popup. < style   type ="text/css">        .modalBackground        {              background-color : Gray;              filter : alpha(opacity=80);              opacity : 0.5;       }        .ModalWindow        {              border : solid1px#c0c0c0;              background : #f0f0f0;              padding : 0px10px10px10px;              position : absolute;              top : -1000px;       } </ style > Step 3:   Create an aspx page and add a Gridview with another gridview in the last TemplateField. The last templatefield will also contain a lable which will

Hierarchical GridView in ASP.NET with AJAX, JQuery implementation - Part 1

Previously I had blogged some post related to showing two grids in hierarchical way. For example - when I need to show an invoice reports on the screen, the user requesting to show the list of invoices at initial time and they can drill down the details of item details of each invoice by clicking on respective row. The implementations can be in multiple ways, but I had blogged the implementation with AJAX and without AJAX using Java script on ASP.NET page. Below are the URLs of the same – Hierarchical GridView in ASP.NET Hierarchical GridView in ASP.NET with AJAX, Javascript implementation In this post I am taking the same requirements done before and enhance with some additional functionality as per readers expectations. The requirement on this implementation will be – The page should show a Grid View with list of Orders with Expand icon on the first column. On click of expand icon on each row, the Order Details of the Order must be fetched from the database

Scrollable Gridview With fixheader using JQuery in Asp.net

Scrollable Gridview With fixheader using JQuery in Asp.net Introduction: In this article I will explain how to implement scrollable gridview with fixed header in asp.net using JQuery.  Description:  In Previous posts I explained lot of articles regarding Gridview. Now I will explain how to implement scrollable gridview with fixed header in asp.net. I have one gridview that contains lot of records and I used  paging for gridview  but the requirement is to display all the records without paging. I removed paging at that time gridview occupied lot of space because it contains more records to solve this problem we implemented scrollbar.  After scrollbar implementation if we scroll the gridview we are unable to see Gridview header.   To implement Scrollable gridview with fixed header I tried to implement concept with css and JavaScript but there is no luck because maintaining fixed header working in IE but not in Mozilla and vice versa to solve this browser compatibility proble