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

GRIDVIEW GROUPING

When displaying data, we sometimes would like to group data for better user experience or when displaying long list of hierarchal data, we would want to display them in a tree view kind of structure. There is more than way of doing this, but I am going to explain achieving this functionality using  AJAX Collapsible Panel Extender Control . Overview: I am going to use  Adventure Works  as datasource. Every product in  Production.Product  table belongs to a product sub category. We fetch handful of products and the sub categories they belong to from the database. Our objective is to list all the available sub categories and allow user to  expand/collapse  to look/hide the list of products belonging to each subcategory. Database Connection Added following entry under  connectionStrings  element in  web.config . < add   name = "Sql"   connectionString="Data Source=(local); Initial  Catalog = AdventureWorks ...

Dynamic Generation of Word Document Report in ASP.NET with HTML

Overview Ever needed to generate Word documents from your ASP.NET applications? There are a couple of components which will help to generate Word documents, but using these components may have some overhead such as Component Registration, setting permissions, licenses, etc., Sometimes, it may even become difficult to understand their features and use them. Generating word document in ASP.NET with HTML is incredibly easy. The following sample demonstrates how to place Heading and Table dynamically in the word document in ASP.NET web applications using HTML. Requirements Microsoft Visual Web Developer 2005 Express Edition Create the Web Application project Add the new Web Site Application project (with name as Generate Word Document) and place the button (with name as btnGenerateDocument) in the Default.aspx web form as shown below. Double click the highlighted code behind file from the Solution Explorer and add the following namespaces. Listing 1 using  System...

GRIDVIEW ZOOM IMAGE

When you have images in your  GridView , you would most likely show them as thumbnails so as to not distort the whole layout. However user would want to look at the full image by clicking on the image or just hovering his mouse over it. In today’s applications, this is a basic requirement and there are just so many third party controls or plugins which would support this functionality. I am going do this conventional way using  javascript  way in this article.  On top of it, I am also going to explain how to get images from database using  HttpHandlers . Example: I am using  Adventure Works  as datasource. We fetch handful of products and bind them to the grid. When page is initially loaded, we retrieve products from Production . Product  table and bind them to the grid. We display some product attributes such as Product ID, Product Number, Product Name, List Price and product’s thumbnail. When user hover his mouse on the page, we fetch the f...