tags:

views:

10358

answers:

12

Can anyone tell the function to sort the columns of a gridview in c# asp.net.

The databound to gridview is from datacontext created using linq. I wanted to click the header of the column to sort the data.

Thanks!

+2  A: 

http://msdn.microsoft.com/en-us/library/ms745786.aspx

http://aspnet.4guysfromrolla.com/articles/012308-1.aspx

Kon
The MSDN article works great, except you need to change one line of code in the .cs file: `string header = ((Binding)headerClicked.Column.DisplayMemberBinding).Path.Path;` The way the code is on MSDN, sorting will only work if the header and column name are exactly the same.
Jared Harley
A: 

more information on sorting in a gridview can be found here: MSDN Gridview sorting the methodology used to get the data should not matter, you can use the same sorting.

Jeremy B.
A: 

My code for grid view is given below..: I need a sort function in c# when the column header is clicked.

   <asp:GridView ID="GridView1" runat="server"  
    OnSortCommand="SortCommand_OnClick" AutoGenerateColumns="False" CellPadding="4" 
    ForeColor="#333333" GridLines="None"
    onselectedindexchanged="GridView1_SelectedIndexChanged" >
    <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
    <Columns>
        <asp:BoundField DataField="ProgramVersion" HeaderText="Version" />
        <asp:TemplateField HeaderText="Date / Time" SortExpression="OperationTime">
            <EditItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%# Eval("OperationTime") %>'></asp:Label>
            </EditItemTemplate>
            <ItemTemplate>
                <asp:Label ID="Label2" runat="server" Text='<%# Bind("OperationTime") %>'></asp:Label>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField DataField="DomainUser" HeaderText="DomainUser" ReadOnly="True" 
            SortExpression="DomainUser" />
        <asp:BoundField DataField="Operation" HeaderText="Operation" 
            ReadOnly="True" SortExpression="Operation" />
        <asp:BoundField DataField="ComputerName" HeaderText="ComputerName" ReadOnly="True" 
            SortExpression="ComputerName" />
        <asp:BoundField DataField="IPaddress" HeaderText="IPaddress" 
            SortExpression="IPaddress" ReadOnly="True" />
        <asp:CheckBoxField DataField="OnNetwork" HeaderText="OnNetwork" ReadOnly="True" 
            SortExpression="OnNetwork" />
        <asp:HyperLinkField HeaderText="RIS" NavigateUrl="RIS.aspx" Text="Log" />
        <asp:HyperLinkField HeaderText="Sync" NavigateUrl="Sync.aspx" Text="Log" />
    </Columns>

    <EmptyDataTemplate>
        No Data to Display!
    </EmptyDataTemplate>
    <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
    <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
    <EditRowStyle BackColor="#999999" />
    <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
A: 

add:

  AllowSorting="true"

to the <asp:GridView /> tag, that should do it

craigmoliver
A: 

No Craigmoliver....When I do that Alone it gives an error "The GridView 'GridView1' fired event Sorting which wasn't handled."

Hence I got to write a function to handle the sorting.

A: 

When I do that Alone it gives an error "The GridView 'GridView1' fired event Sorting which wasn't handled.

I've had that happen before... I've just created a throwaway handler, and then everything seemed to start working after that. Not the prettiest solution, but it worked for me.

That said, I didn't see any reference to a data source in your GridView code. You'll need something like this:

<asp:LinqDataSource ID="dsMyDataSource" runat="server"
DataContextTypeName="MyDataContext"
TableName="MyTable"
AllowSort="true" />

And then in your GridView:

<asp:GridView ID="gvMyGridView" runat="server" DataSourceID="dsMyDataSource" ... />
Daniel Schaffer
A: 

I do not use a datasource. I use a query to bind the data with grid. The query is as below.

  var query1 = from u in dc.Usage_Computers
                                     where u.DomainUser == s3
                                     orderby u.OperationTime descending
                                     select new
                                     {
                                         u.ProgramVersion,
                                         u.OperationTime,
                                         u.IPaddress,
                                         u.ComputerName,
                                         u.DomainUser,
                                         u.OnNetwork,
                                         Operation = u.Operation == 1 ? "Login" :
                                                     u.Operation == 2 ? "Logoff" :
                                                     u.Operation == 3 ? "AGNSConnect":
                                                     u.Operation == 4 ? "AGNS   
                                                                         Disconnect" :
                                                     "None"
                                     };

Now since I do not use a datasource I have to write my own function for sorting I think. Can anyone give me inputs on this?

A: 

In the Properties Panel double Click on the Sorting Entry. A new Function will be created. In this Function write the Code to fill the Gridview. The only difference is to change the query based on GridViewSortEventArgs e

e.SortExpression and
e.SortDirection allways Ascending :-(

I hope this very short Answer helps

Georg
A: 

I am not sure about the code which I have to write for the sorting function which you have told. Can you give me some example.?

A: 

In Half Pseudocode for SQL Query

string Query= string.Empty;
string SortExpression = string.Empty;

// HDFSort is an HiddenField !!!

protected void SortCommand_OnClick(object sender, GridViewSortEventArgs e)
{
   SortExpression = e.SortExpression; 
   Query = YourQuery + " ORDER BY "+SortExpression +" "+ HDFSort.Value ;
   HDFSort.Value = HDFSort.Value== "ASC" ? "DESC" : "ASC";
   RefreshGridView();
}

protected void RefreshGridView()
{
   GridView1.DataSource = DBObject.GetData(Query);
   GridView1.DataBind();
}
Georg
+4  A: 

There are 2 things you need to do to get this right.

  1. Keep the sorting state is viewstate(SortDirection and SortExpression)
  2. You generate the correct linq expression based on the current sorting state.

Manually handle the Sorting event in the grid and use this helper I wrote to sort by SortExpression and SortDirection:

public static IQueryable<T> SortBy<T>(IQueryable<T> source, string sortExpression, SortDirection direction) {
    if (source == null) {
        throw new ArgumentNullException("source");
    }

    string methodName = "OrderBy";
    if (direction == SortDirection.Descending) {
        methodName += "Descending";
    }

    var paramExp = Expression.Parameter(typeof(T), String.Empty);
    var propExp = Expression.PropertyOrField(paramExp, sortExpression);

    // p => p.sortExpression
    var sortLambda = Expression.Lambda(propExp, paramExp);

    var methodCallExp = Expression.Call(
                                typeof(Queryable),
                                methodName,
                                new[] { typeof(T), propExp.Type },
                                source.Expression,
                                Expression.Quote(sortLambda)
                            );

    return (IQueryable<T>)source.Provider.CreateQuery(methodCallExp);
}

db.Products.SortBy(e.SortExpression, e.SortDirection)

Check out my blog post on how to do this:

dfowler
How can your sort method handle sub-objects. Eg. you have an Order object which contains order.comment.rating, and you want to sort by the rating?
Dofs
You'd have to manually walk the dots of the sortExpression passed in. Its pretty trivial to change the code to handle that.
dfowler
A: 

I found this: http://forums.asp.net/t/956540.aspx but sincerely that forum thread is a mess, and the website where supposedly there is a complete sample is down.

rec