Extending the GridView's Sorting Capabilities
page 2 of 6
by souri challa
Feedback
Average Rating: 
Views (Total / Last 10 Days): 49965/ 145

Adding New Properties to the Custom GridView

[Download Code]

Before we extend the control, let us determine the new properties we would like to have in the control.

  • AllowMultipleColumnSorting: When set to true, this should enable sorting on more than one column.
  • SortAscImageUrl and SortDescImageUrl: These properties allow the page developer to optionally select an image for indicating the sort direction in the column header.  When these properties are left blank, the control inserts a glyph symbol to indicate the sort direction.  We would like to enable the sort direction indicator for default (single-column) sort behavior, too.

The following code block shows how we define the new properties.

Listing 2

        /// <summary>
        /// Enable/Disable MultiColumn Sorting.
        /// </summary>
        [
        Description("Whether Sorting On more than one column is enabled"),
        Category("Behavior"),
        DefaultValue("false"),
        ]
        public bool AllowMultiColumnSorting
        {
            get
            {
                object o = ViewState["EnableMultiColumnSorting"];
                return (o != null ? (bool)o : false);
            }
            set
            {
                AllowSorting = true; //Set default Sort property to true
                ViewState["EnableMultiColumnSorting"] = value;
            }
        }


        /// <summary>
        /// Get or Set Image location to be used to display Ascending Sort order.
        /// </summary>
        [
        Description("Image to display for Ascending Sort"),
        Category("Misc"),
        Editor("System.Web.UI.Design.UrlEditor", typeof(System.Drawing.Design.UITypeEditor)),
        DefaultValue(""),       
        ]
        public string SortAscImageUrl
        {
            get
            {
                object o = ViewState["SortImageAsc"];
                return (o != null ? o.ToString() : "");
            }
            set
            {
                ViewState["SortImageAsc"] = value;
            }
        }
        /// <summary>
        /// Get or Set Image location to be used to display Ascending Sort order.
        /// </summary>
        [
        Description("Image to display for Descending Sort"),
        Category("Misc"),
        Editor("System.Web.UI.Design.UrlEditor", typeof(System.Drawing.Design.UITypeEditor)),
        DefaultValue(""),
        ]
        public string SortDescImageUrl
        {
            get
            {
                object o = ViewState["SortImageDesc"];
                return (o != null ? o.ToString() : "");
            }
            set
            {
                ViewState["SortImageDesc"] = value;
            }
        }

The design-time attributes for the properties are worth noting.  The Category, Description, and DefaultValue attributes allocate the properties to the corresponding classification in the IDE's Property Browser. The Editor attribute enables a URL Editor for easily choosing the image location.


View Entire Article

User Comments

Title: Using the Extended GridView Control on a Web Form   
Name: Using the Extended GridView Control on a Web Form
Date: 2012-05-16 12:30:50 PM
Comment:
nice
Title: None of that is necessary -- use this code instead   
Name: A random ASP.NET junkie
Date: 2012-04-25 7:08:33 PM
Comment:
protected void gridViewSorting(object sender, GridViewSortEventArgs e)
{

//
// This odd function permits GridView objects to sort on multiple columns
// Without this function, a GridView object does not sort correctly when multiple
// columns are named in its sort specification.
//

if (!(sender is GridView))
{
return;
}
if (!e.SortExpression.Contains(','))
{
return;
}

GridView gv = sender as GridView;

//
// Find the column that is to become the basis of the sort
//
foreach (DataControlField dc in gv.Columns)
{
String fieldSortExprClean = dc.SortExpression.Replace(" DESC", "");
fieldSortExprClean = fieldSortExprClean.Replace(" ASC", "");

String eventSortExprClean = e.SortExpression.Replace(" DESC", "");
eventSortExprClean = eventSortExprClean.Replace(" ASC", "");

if (fieldSortExprClean == eventSortExprClean)
{
if (e.SortDirection == SortDirection.Ascending)
{
dc.SortExpression = fieldSortExprClean.Replace(",", " ASC,");
e.SortExpression = fieldSortExprClean.Replace(",", " ASC,");
}
else
{
dc.SortExpression = fieldSortExprClean.Replace(",", " DESC,");
e.SortExpression = fieldSortExprClean.Replace(",", " DESC,");
}
}
}
}
Title: Extending the GridView's Sorting Capabilities   
Name: cyjob668@hotmail.ca
Date: 2011-11-27 6:35:44 PM
Comment:
Hi I looking for the source code, do you know where I can find? Thanks
Title: No source code available   
Name: Vidit
Date: 2011-01-18 7:22:25 AM
Comment:
from where i will get source code,because from above link I m not able to download the code
Title: Where is the source code?   
Name: Pushpendra Rishi
Date: 2010-09-08 9:52:38 AM
Comment:
HEllo,
It appears that the source code is no longer available, please can you let us know where to download it?

Thanks
Title: miss   
Name: Bhargavi
Date: 2010-04-01 9:39:54 AM
Comment:
Hi i had a problem when working multiple users working on same form.

we had a grid with sorting and paging , when searching and paging data is shared b/w all users.

if any sugessions, send me to bhargavi.code@gmail.com

thanks in advance.
Title: CEO KC   
Name: Puh Källsbo
Date: 2009-09-16 3:12:05 PM
Comment:
Kick as code!
Saved me from burning the midnight oil longer than needed!
Title: Lonely Soul   
Name: Lonely Soul
Date: 2009-06-29 2:44:48 AM
Comment:
Very nice article! thanks
Title: How to sort in numbers in Gridview control using ASP.net with C#   
Name: vathana
Date: 2009-03-14 2:56:59 AM
Comment:
I have to sort the numbers (for example: Employee-ID) in gridview control using ASP.net with C#,i am using the sorting methog in ASP.net it sort this way i.e. 1 11 121 2 23 3....this order i need sequential order only i.e., 0 1 2 3.....this order only. how can i use it..........
Title: Thank you   
Name: Denis
Date: 2009-01-28 7:02:19 AM
Comment:
I'm sorry.. My english is too bad.
But I think, that you should make some changes in DisplaySortOrderImages method.

if (sortImgLoc != String.Empty)
{
Image imgSortDirection = new Image();
imgSortDirection.ImageUrl = sortImgLoc;
dgItem.Cells[i].Controls.Add(imgSortDirection);
Label lblSortOrder = new Label();
lblSortOrder.Font.Size = FontUnit.Small;
lblSortOrder.Text = sortOrderNo.ToString();
dgItem.Cells[i].Controls.Add(lblSortOrder);
}

must change on

if (sortImgLoc != String.Empty)
{
Image imgSortDirection = new Image();
imgSortDirection.ImageUrl = sortImgLoc;
dgItem.Cells[i].Controls.Add(imgSortDirection);
if(AllowMultiColumnSorting) {
Label lblSortOrder = new Label();
lblSortOrder.Font.Size = FontUnit.Small;
lblSortOrder.Text = sortOrderNo.ToString();
dgItem.Cells[i].Controls.Add(lblSortOrder);
}
}
Title: You are genius!!!   
Name: Ram
Date: 2008-12-05 5:33:19 PM
Comment:
Hello there,

Thanks for the wonderful article. It helped me lot and you saved my time.

I have customized the code little bit according to my requirement.

Thank you so much. Keep it up.
Title: Unauthorised Access   
Name: Vikram
Date: 2008-09-04 1:40:56 AM
Comment:
http://beta.asp.net/quickstart/aspnet/doc/ctrlref/data/gridview.aspx

what is username and password to access this url?
Title: Want code without SQLDatasource   
Name: Akhil Raj
Date: 2008-07-09 12:32:56 AM
Comment:
hi,
i read this articles more time. very interesting. I always missed something. but now got it is working with only sql data source. can u give the idea for same concept with out using sqldatasource. want to work with coding ..
Title: Without sqldatasourse, the sort don't work   
Name: Tony
Date: 2008-06-20 2:03:26 PM
Comment:
When I use datasource object (sql, oracle, access etc ...) the sorting with image icon always working, but when I use 3 tire app, binding with code bind like
gridview.datasource = BLL.GetData(), the sort image never work because gridview.sortExpression always empty under rowCreate and it only happen ones before sort event, not after sort, any idea for it, is I must use datasource object?
Title: Excellent   
Name: Gopal Krishna Rao
Date: 2008-02-26 4:49:01 AM
Comment:
I have used this technique in our existing project and Succeeded with Object Data Source which Returns Generic List Collections. We have extended the sorting technique by writing a separate class for multiple columns (or properties).

Thanks for the great solution.

Gopal Krishna
Nunet technologies Ltd.
vedagopal2004@gmail.com
Title: Use SQLDataSource   
Name: GaneshNaidu
Date: 2007-12-03 1:01:27 AM
Comment:
I had to use a sqldatasoruce to get the paging and sorting to work for a inherited grid. I manually create a sqldatasoruce in code and pass the ID to the grid.

Dim sqlDS As New SqlDataSource(System.Configuration.ConfigurationManager.ConnectionStrings("NegConnString").ConnectionString, sqlToUse)
sqlDS.ID = "sqlDS"
sqlDS.DataBind()
Me.Controls.Add(sqlDS)

Dim ug As uControls.uGridView = BuildGrid()

ug.DataSourceID = "sqlDS"
Title: Use SQLDataSource   
Name: Ustes
Date: 2007-11-01 6:58:32 PM
Comment:
I had to use a sqldatasoruce to get the paging and sorting to work for a inherited grid. I manually create a sqldatasoruce in code and pass the ID to the grid.

Dim sqlDS As New SqlDataSource(System.Configuration.ConfigurationManager.ConnectionStrings("NegConnString").ConnectionString, sqlToUse)
sqlDS.ID = "sqlDS"
sqlDS.DataBind()
Me.Controls.Add(sqlDS)

Dim ug As uControls.uGridView = BuildGrid()

ug.DataSourceID = "sqlDS"
Title: title from other place   
Name: kunni
Date: 2007-09-27 2:54:13 AM
Comment:
It is good, but i ahve a requirement i want ot sort a column. for that column i am getting header name from db. how can i sort that column.
Title: how to work with SortExprection   
Name: GaneshNaidu
Date: 2007-09-22 2:07:53 PM
Comment:
what is sort and how to work
Title: how to do columns sorting in girdview control   
Name: bannu
Date: 2007-08-20 7:59:34 AM
Comment:
The code wht u have said is by using sql data source control.But my requirement is how to do columns sorting in gridview control without using
a sql datasource control(means by writing sql conncetion string code in web.config file)
Title: Nice work ddod   
Name: Bombadil
Date: 2007-08-16 9:54:53 AM
Comment:
It is rare to find a free custom control free of bugs that just works. really nice.

thanks
Title: Great   
Name: Chuck Snyder
Date: 2007-06-29 11:07:06 AM
Comment:
Thanks. I know this is an old item, but works great. I converted it to VB.Net as a Web Control and it solved a problelm I've had.
Title: OnSorting event   
Name: Tom
Date: 2007-01-06 12:56:21 PM
Comment:
Hi,

I have added this to one of my asp.net pages. I bind the fields in the code behind from a dataview, however I can't get it working. Whenever I click on the headers of the gridview its looking for an OnSort event. If I add it, it then doesn't work?...
Title: Adding Atlas support ?   
Name: Fullmobile
Date: 2006-11-14 6:17:40 AM
Comment:
Nice article. I would suggest adding AJAX support for this grid to push it further. Making the sort operation invisible to the client and avoid refreshes.
Title: Won't work properly   
Name: Jason Law
Date: 2006-10-31 2:35:51 AM
Comment:
This Extended Grid View won't work properly on its multiple column sorting function if there is at least one column whose name is the subset of another column's name.

For example, if there are columns which names are 'Country' and 'Country_Name'. The column 'Country' starts with the word Country and the column 'Country_Name' also starts with the word Country. Therefore, both columns share the same sort order. Under normal circumstances, none of the columns should have the same sort order.
Title: How do this without DataSourceId   
Name: Seb
Date: 2006-10-12 6:47:15 AM
Comment:
I don't use a DataSourceId so the code don't work (ie : SortExpression is always empty...)

can you help me ? Thanks
Title: Why is the DB queried on each click   
Name: Paul
Date: 2006-10-11 5:13:27 PM
Comment:
Well, I'm not sure if this is useful when there is a large ( multi-table join ) query used for the results.

Doesn't this technique require re-querying the DB everytime their is a click on a LinkButton.

Wanted to see how others how used this when performance is an issue.

Thanks, Paul
Title: GridView Sort Does Support Sorting On Muliple Columns   
Name: Craig
Date: 2006-10-05 2:08:21 PM
Comment:
GridView Sort Does Support Sorting On Muliple Columns

Set the SortExpression of a column to Field1,Field2 and it will sort on 2 fields
Title: Thanks for greate this artical   
Name: Anil Desai
Date: 2006-09-30 2:37:33 AM
Comment:
Thanks for providing such type of collactions of source codes
Title: aha   
Name: Kristen
Date: 2006-08-23 11:45:37 AM
Comment:
I figured out the difference between my stuff and yours, my DAL returns a list rather than a dataset.
Title: Sort image with Obj Data Source?   
Name: Kristen
Date: 2006-08-22 2:26:41 PM
Comment:
This seems to work great for me as long as i use and sqldatasource. But when I tried it with an ObjectDataSource I no longer get the sort arrows in the column header. Is there maybe something I'm missing?
Title: Convert to VB   
Name: Grace
Date: 2006-07-10 2:26:07 PM
Comment:
Hi! Can anyone convert this to VB? Thanks!
Title: Work with dataview?   
Name: Pete
Date: 2006-05-23 1:17:10 PM
Comment:
Would there be a way to use this so it doesn't depend on using an ObjectDataSource? I want the functionality, but I need to use something that doesn't keep hitting the database (which the dataset and objectdatasource solution does). I get my dataset, then bind the gridview to the dataview, and it works, but I'm having to rebuild all of the sorting and paging functions (and add in my own multisort eventually). It would be really nice to be able to use this article though - it's much more elegant than what I'm coming up with!
Title: I got it   
Name: Pete
Date: 2006-05-10 4:52:21 PM
Comment:
I think I figured out what my problem was - my query was getting a null value sometimes in the ObjectDataSource. So I think I'm all good now. Disabling EnableSortingAndPagingCallback and instead using Atlas updatepanels did the trick for no flickers, too, even with multisort. Woohoo! Now I just need to see if I can find a way to toggle easily between "single" and multicolumn sorts....
Title: EnableSortingAndPagingCallback   
Name: Pete
Date: 2006-05-09 3:23:48 PM
Comment:
Ahhh, I found out my problem - it doesn't seem to work with EnableSortingAndPagingCallback enabled. Is this possible? I really wanted to "Atlas"-fy this!
Title: Almost there, but still not working   
Name: Pete
Date: 2006-05-09 2:07:43 PM
Comment:
Awesome article! It's almsot exactly what I'm looking for, and it sort of works. I've got the sorting down, but the multisort doesn't work. It sorts o none column, but doesn't update the graphic when I toggle the column, and doesn't do the multicolumn sort at all even though it's enabled. Any ideas?
Title: Skin for gridview   
Name: Vee
Date: 2006-04-20 9:33:04 AM
Comment:
Larry,
You have mentioned that you made it working with skin file. Can you please explain? I'm not sure where exactly i need to add it. Please reply.
Thanks,
Vee
Title: Never mind about dataset   
Name: larry
Date: 2006-03-06 2:57:02 PM
Comment:
Got it working! I converted code from C Sharp to VB and then had to store sort expression in viewstate and then it worked. I have it working with skins, you just have to add the register tag like it is in the html and the control tag like it is in the html.
Title: Define SKIN   
Name: Gautam
Date: 2006-03-06 2:02:12 PM
Comment:
Not able to define a Skin for this control
Title: Non-declarative version   
Name: larry
Date: 2006-03-06 11:14:57 AM
Comment:
I would like to use this but with a dataset. I can't use object data source because you can't pass properties to the object datasource from a page base class. From walking through it, seems to fail because it doesn't call the "OnRowCreated" twice for the header (once before sort, and then again after sort). If you do it with dataset seems to call it once before sort. Any ideas?
Title: be carrefull about field name comparisons   
Name: alexis
Date: 2006-03-01 12:56:55 PM
Comment:
I, your component is just what i needed but i modified 2 lines of your source code (of the MultiSortGridView.cs) to replace "startsWith" by "Equals". because the name of one of my fields in the gridView is used for the beginning of the name of some of the others fields.
Consequently :
"if (sortColumns[i].StartsWith(sortColumn))" (line 59)is now "if (sortColumns[i].Equals(sortColumn))"
and "if (sortAttribute.IndexOf(e.SortExpression) > 0 || sortAttribute.StartsWith(e.SortExpression))" (line 124) is now for me "if (sortAttribute.IndexOf(e.SortExpression) > 0 || sortAttribute.Equals(e.SortExpression))"

You did a great work, thanks !!! Alexis
Title: EnableSortingAndPagingCallback   
Name: Kevin M
Date: 2006-02-06 5:48:33 PM
Comment:
Is there anyway to get this to work with EnableSortingAndPagingCallback = true?
Title: Very Nice but..   
Name: Moe Kazzaz
Date: 2006-01-13 5:25:00 PM
Comment:
Thanks for the great article.

I couldn't get multisort to work with callbacks enabled. Am I missing something?

Thanks.
Title: Has anyone built this class file in VB?   
Name: Randy
Date: 2006-01-01 8:13:47 PM
Comment:
This looks great...downloaded the sample, works nicely. However, I need it in VB to incorporate into my project, and sorry to say, I don't know how to confidently convert this class into a VB class. Has anyone done that or can point me toward a VB solution for this?
Title: Beautiful   
Name: NET 2.0 Coder
Date: 2005-12-06 8:13:54 PM
Comment:
Even works perfectly with EnableSortingAndPagingCallback, implementing postback free sorting and paging.

Thanks!
Title: Working with Object Datasource.   
Name: Souri Challa
Date: 2005-07-25 2:45:55 AM
Comment:
There should not be any difference, as long as the above gridview control is bound to an object datasource that uses a Dataset. I have added a new page ObjData.aspx to the test project sample to demonstrate this.
Title: sort direction   
Name: Jon Stranger
Date: 2005-07-24 7:18:08 AM
Comment:
A useful article. I have implemented multi-column sorting (in VB) loosely based on your approach (i.e. with an event handler that overrides OnSorting and manipulates e.SortExpression before calling the base OnSorting method) but using an ObjectDataSource with a SelectMethod that returns a DataSet.

Basic multi-column sorting works, but I cannot get reverse sort direction to work. As I am sure you know, changing e.SortDirection only operates on the last column specified in SortExpression, but if I include ‘ ASC’ or ‘ DESC’ after a column name in SortExpression then it fails with something like ‘column x ASC not recognised’. I suspect that SqlDataSource and ObjectDataSource work differently in this respect and that I will have to do my own DataView sort and rebind the GridView rather than just calling the base OnSorting method – but I am not sure how to do this. Any ideas?
Title: What about Dataset instead of SqlDataSource?   
Name: Souri
Date: 2005-07-01 2:41:51 AM
Comment:
The Key here for "Only Declartive code" sorting is for the UI layer to know how to connect to the next layer.
In your case, you can bind an Object Data Source control to the GridView and supply a 'SelectMethod' that returns a dataset.
Title: What about Dataset instead of SqlDataSource?   
Name: Kanaiya Parmar
Date: 2005-06-30 7:57:32 PM
Comment:
You have used SqlDataSource to bind with GridView. What-If I want to use DataSet coming out of BLL/DAL layer. Will it support sorting/paging out of the box? If not, what is the way to achieve it?

Because normally we won't use much SqlDataSource in n-tier environment when either dataset or collection object travels between the tiers.

Look forward to your response.

Thanks,
Kanaiya
Title: Great Article !!!!   
Name: Carlos Lone
Date: 2005-06-25 7:34:23 PM
Comment:
Thanks for the Article.

The code is clean, and is pretty well explained.

Congrats !!!, Souri challa !!!!

Product Spotlight
Product Spotlight 





Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-10-06 9:07:00 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search