Saturday, 24 January 2009

Setting the Initial Sort Order – Dynamic Data

This is just a quick note on a post I made on the Dynamic Data Forum to answer a question where setting the DisplayColumnAttribute should set the default sort order of the GridView on the List page but didn’t. Here’s how I solved it with a hint or two from Marcin Dobosz.

[MetadataType(typeof(Orders_Metadata ))]
[DisplayColumn("OrderID", "OrderID", true)]
public partial class Orders
{
    public class Orders_Metadata
    {
... }
}

Listing 1 – Example Metadata

Assuming you have a table with the DisplayColumnAttribute set you could put this on your List page: 

var displayColumn = table.GetAttribute<DisplayColumnAttribute>();
if (displayColumn != null && displayColumn.SortColumn != null)
{
    GridView1.Sort(displayColumn.SortColumn,
        displayColumn.SortDescending ? SortDirection.Descending : SortDirection.Ascending);
}

Listing 2 – Edit the Page_Load event handler and add the following code

public static T GetAttribute<T>(this MetaTable table) where T : Attribute
{
    return table.Attributes.OfType<T>().FirstOrDefault();
}

Listing 3 – you will also need this extension method see Writing Attributes and Extension Methods for Dynamic Data

Add your DisplayColumnAttribute (see Listing 1) to the table you want sorted (note: it must have the second string constant even if it’s the same name, as the second string it the one that the sort is done on, and the third value if true causes the sort to be descending). Then in Listing 2 you get the attribute using the extension method from Listing 3 and apply the relevant sort.

This is here mainly so I can find it again! HappyWizard

7 comments:

Anonymous said...

Using this method, deletes don't work anymore...

Steve said...

I'll give that a test and get back to you on this, I think only tested this with DD.

Steve :D

Stuart Whiteford said...

Yep, deletes don't work for me too. Also noticed that I can only navigate up to page 2 with the GridViewPager.

Stuart Whiteford said...

Steve,

Instead of sorting on the GridView, I set the OrderBy property of the underlying LinqDataSource in The Page_Load method and that seems to resolve the deleting and paging issues.

[code]
string orderBy = string.Format("{0} {1}", displayColumn.SortColumn, displayColumn.SortDescending ? "descending" : "ascending");
GridDataSource.OrderBy = orderBy;
[/code]

Anonymous said...

not much help for a newbie...

Steve said...

Hi Stuart, thanks for that, I'll do an update and cite you for that snippet, do you have a blog or website I can point to in the citation?

Steve :D

Gareth Thomas Hill said...

Thanks again for this - solved my problem!

Post a Comment