Solved

ASP.NET: How to sort a GridView bound to a generic List

Posted on 2009-07-03
6
804 Views
Last Modified: 2013-12-17
Hi all,

I have a gridview that I bind to a generic list in memory. I would like to know how I can sort that the gridview depending on the column clicked.
using System;
using System.Collections.Generic;
using System.Text;
 
namespace testList
{
    public class TestElement 
    {
        
        private int _id = null;
 
        private String _name = null;
 
        private int _age = null;
 
        private decimal _salary = null;
 
        private int _reportTo = null;
 
 
        public int Id
        {
            get { return _id; }
            set { _id = value; }
        }
 
        public String Name
        {
            get { return _name; }
            set { _name = value; }
        }
 
        public int Age
        {
            get { return _age; }
            set { _age = value; }
        }
 
        public decimal Salary
        {
            get { return _salary; }
            set { _salary = value; }
        }
 
        public int ReportTo
        {
            get { return _reportTo; }
            set { _reportTo = value; }
        }
 
    }
}
 
 
 
 
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Threading;
using testList;
 
public partial class testPage : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridView grid = new GridView;
            List<TestElement> source = //Get the list
            grid.DataSource=source;
            grid.DataBind();
            
            Page.Controls.Add(grid);
        }
    }
}

Open in new window

0
Comment
Question by:karakav
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
6 Comments
 
LVL 12

Expert Comment

by:Nirmalan Nagenthiran
ID: 24771144
0
 
LVL 9

Expert Comment

by:Rahul Goel ITIL
ID: 24771264
0
 
LVL 20

Accepted Solution

by:
ddayx10 earned 500 total points
ID: 24771402
Well shucks. Here's a sample that does just that :)

I changed your object around a bit to fit my dev database, and simplified it for my convenience. It should give you the full picture of how to answer your question and it's pretty darn close to your code.

For the sorting, this should likely be implemented into your class more fully, but that is a large task and this works just fine for what you gave me to start with.

Check it out.

PS: Also threw in some new 3.5 property techniques you can check out...
****ASPX CODE****
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default28.aspx.cs" Inherits="Pages1_Default28" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
		<asp:GridView ID="gv" runat="server" AllowSorting="true" 
			AutoGenerateColumns="false" OnSorting="gv_Sorting">
			<Columns>
				<asp:BoundField HeaderText="ID" DataField="ID" SortExpression="ID" />
				<asp:BoundField HeaderText="Fname" DataField="fName" SortExpression="fName" />
				<asp:BoundField HeaderText="Lname" DataField="lName" SortExpression="lName" />
				<asp:BoundField HeaderText="Nname" DataField="nName" SortExpression="nName"/>
			</Columns>
		</asp:GridView>
    </form>
</body>
</html>
 
 
****CODE BEHIND****
 
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Data.SqlClient;
 
public partial class Pages1_Default28 : System.Web.UI.Page
{
    public string connStr
    {
        get{ return ConfigurationManager.ConnectionStrings["conn"].ToString(); }
    }
 
 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            bindData();
            ViewState["_lastSortDirection"] = "DESC";
        }
    }
 
 
 
 
    private void bindData()
    {
        List<TestElement> dSource = new List<TestElement>();
 
        SqlConnection conn = new SqlConnection(connStr);
        SqlCommand cmd = new SqlCommand("SELECT * FROM DevTable", conn);
        conn.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        while(dr.Read())
        {
            TestElement ts = new TestElement();
            ts.Id = Convert.ToInt32(dr["testID"]);
            ts.fName = dr["fName"].ToString();
            ts.lName = dr["lName"].ToString();
            ts.nName = dr["nName"].ToString();
            dSource.Add(ts);
        }
        dr.Close();
        conn.Close();
        conn.Dispose();
        Session["dSource"] = dSource;
        gv.DataSource = dSource;
        gv.DataBind();
    }
 
    protected void gv_Sorting(object sender, GridViewSortEventArgs e)
    {
        List<TestElement> dSource = (List<TestElement>)Session["dSource"];
        switch (e.SortExpression)
        {
            case "ID":
                if (lastSortDirection() == "ASC")
                {
                    dSource.Sort(delegate(TestElement p1, TestElement p2) { return p1.Id.CompareTo(p2.Id) * -1; });
                }
                else
                {
                    dSource.Sort(delegate(TestElement p1, TestElement p2) { return p1.Id.CompareTo(p2.Id); });
                }
                break;
            case "fName":
                if (lastSortDirection() == "ASC")
                {
                    dSource.Sort(delegate(TestElement p1, TestElement p2) { return p1.fName.CompareTo(p2.fName) * -1; });
                }
                else
                {
                    dSource.Sort(delegate(TestElement p1, TestElement p2) { return p1.fName.CompareTo(p2.fName); });
                }
                break;
            case "lName":
                if (lastSortDirection() == "ASC")
                {
                    dSource.Sort(delegate(TestElement p1, TestElement p2) { return p1.lName.CompareTo(p2.lName) * -1; });
                }
                else
                {
                    dSource.Sort(delegate(TestElement p1, TestElement p2) { return p1.lName.CompareTo(p2.lName); });
                }
                break;
            case "nName":
                if (lastSortDirection() == "ASC")
                {
                    dSource.Sort(delegate(TestElement p1, TestElement p2) { return p1.nName.CompareTo(p2.nName) * -1; });
                }
                else
                {
                    dSource.Sort(delegate(TestElement p1, TestElement p2) { return p1.nName.CompareTo(p2.nName); });
                }
                break;
        }
        gv.DataSource = dSource;
        gv.DataBind();
        Session["dSource"] = dSource;
    }
 
 
    private string lastSortDirection()
    {
        if (ViewState["_lastSortDirection"] == null || String.IsNullOrEmpty(ViewState["_lastSortDirection"].ToString()))
        {
            ViewState["_lastSortDirection"] = "DESC";
            return ViewState["_lastSortDirection"].ToString();
        }
        else
        {
            if (ViewState["_lastSortDirection"].ToString() == "DESC")
            {
                ViewState["_lastSortDirection"] = "ASC";
                return ViewState["_lastSortDirection"].ToString();
            }
            else
            {
                ViewState["_lastSortDirection"] = "DESC";
                return ViewState["_lastSortDirection"].ToString();
            }
        }
    }
}
 
 
 
public class TestElement
{
 
    public int Id
    {
        get;
        set;
    }
 
    public String fName
    {
        get;
        set;
    }
 
    public String lName
    {
        get;
        set;
    }
 
    public String nName
    {
        get;
        set;
    }
}

Open in new window

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 20

Expert Comment

by:ddayx10
ID: 24771404
No you other guys...this is the solution :) !!!!
0
 
LVL 20

Expert Comment

by:ddayx10
ID: 24771463
OK thought I'd look, that first one's by NNirmalan is not too bad (only not too bad cause I didn't do it that way, otherwise it's pretty cool)...

I sort the custom object properties, they convert the grid into a dataview and sort that :)

Pick yer poison...off for the weekend says I
0
 
LVL 4

Author Closing Comment

by:karakav
ID: 31599492
Thanks.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Setting up a IIS 8 Web Server to send and receive XML files 7 97
looking for an ASP.net report designer 4 41
Reactjs with .NET 3 76
Adjust the codes 3 33
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
In a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…

733 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question